Generate ISO Date Time in a Batch File

I was looking for a way to generate a log file name variable containing the current date and time. Yes normally I use vbscript and moving to Powershell however it is fun sometimes to rediscover old skills.

Now [cmd]date /t[/cmd] produces (at the cmd.exe in Windows XP) the format [cmd]Day DD/MM/YYYY[/cmd] for example: [cmd]Thu 07/01/2010[/cmd]

Attempting to assign this to a variable like so, does not work
[cmd]SET datenow=date /t[/cmd]
When echoed out this time returns the string: [cmd]date /t[/cmd]

[cmd]SET datenow=%date%[/cmd]
This will now set the variable to the current value of the date. There is no need for the /T.

The same process can be used with setting a variable with the current time: [cmd]SET timenow=%time%[/cmd] which returns the format [cmd]HH:MM:SS.mm[/cmd] Where mm is hundredths of a second.
Example output:[cmd]12:09:58.90[/cmd]

So what I was after was something in the YYYY-MM-DD-HH-MM-SS format. Now that I know how to get the current date and time how do I get the components of them to satisfy the format?

It is possible to return a substring of a variable. I must confess here that I do not the full ins and outs of how the substring capability works howerver I know enough to be dangerous. 🙂 Basically the format is [cmd]%variable:~num_chars_to_skip,num_chars_to_keep%[/cmd]

So how do I return the year only?
[cmd]SET yearnow=%datenow:~10,4%[/cmd]
Returns the year by starting at character 10 and returning the next 4 characters, this example 2010.

Or you can even use the date command, straight up.
[cmd]SET yearnow=%date:~10,4%[/cmd]

Now I simply just need to get all the substrings together into one variable. I could do this a number of ways, one being create a whole bunch of variables for each component, which is long but easy to follow or I can make it a one liner, which is what I chose to do. Here is the result:
[cmd]
echo Get the current date and time in YYYY-MM-DD-HH-MM-SS format
SET isodate=%date:~10,4%-%date:~7,2%-%date:~4,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
echo %isodate%
[/cmd]

This returns: [cmd]2010-01-07-12-09-58[/cmd]

Basically the isodate variable is created by multiple instances of the date and time and combining the use of substring manipulation. Now I can use this variable as part of my log file naming.

References:
http://ss64.com/ntsyntax/varsubstring.html

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.