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).
This is what I've used:
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the
%date%
,date/t
, anddate
that break the original batch-file.It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:
echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
Here is the revised code with comments on why:
--jeroen