Saturday, November 15, 2008

How to get and format date in a bat file

Sooner or later everyone needs to mess up with some batch file Voodoo for some reason - often to pipe the output of some console application into some kind of log file. At this point you'll probably want to put a timestamp on the log file - but you need to reformat the standard date to elminate slashes and stuff. This is how you do it (depending on your operating system):

REM US Operating System: set yyyymmdd=%date:~10%%date:~4,2%%date:~7,2%
REM EU Operating System: set yyyymmdd=%date:~6,4%%date:~3,2%%date:~0,2%

This formats the date into a variable called yyyymmdd (pretty self-explanatory, uh), which you can use later in our lame script in you log file name (or whatever you need it for - In this case I am piping stuff into a log file):

REM EU Operating System
set yyyymmdd=%date:~6,4%%date:~3,2%%date:~0,2%

ECHO myConsoleApp output: >> myLog_%yyyymmdd%.txt
myConsoleApp.exe >> myLog_%yyyymmdd%.txt

This stuff sucks - but I couldn't find the date formatting thing - pretty cryptic, uh? - anywhere on the web (I stole it off a collegue of mine who's kind of a batch files guru) so it might be useful to people.

1 comment:

Anonymous said...

Cool, I just needed that for one of my .cmd script.
DOS is a bit outdated but sometimes it is still usefull...