Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date
. See @npocmaka's https://stackoverflow.com/a/19799236/8479
What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?
I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip
. Is there any easy way I can do this, independent of the regional settings of the machine?
I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.
So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91
:
rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code
I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.
I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
Here's a way to get date time in a single line:
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
And here is a similar batch-file for the time portion.
--jeroen
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
Just use this line:
Short answer :
Long answer