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).
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
This isn't really briefer but might be a more flexible way (credit):
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use
DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
I use this (again not region independent (UK))
Another way (credit):
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
Given a known locality, for reference in functional form. The
ECHOTIMESTAMP
call shows how to get the timestamp into a variable (DTS
in this example.)And saved to file, timestamp.bat, here's the output: