How to get current datetime on windows command line, in a suitable format for using in a filename?

Posted by Rory on Stack Overflow See other posts from Stack Overflow or by Rory
Published on 2008-10-14T22:25:34Z Indexed on 2010/03/20 11:21 UTC
Read the original article Hit count: 328

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 & time as part of the name, eg "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 Win XP Pro. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).

© Stack Overflow or respective owner

Related posts about Windows

Related posts about command-line