Date and 24 hour time batch file variables
I’ve lately been using batch files more and more to do backups and other things.
One of the things that’s given me troubles is using dates and times to add to folders or file names to help with organizing.
What I wanted to end up with is something like 20110211_185530.zip. The first part is the year then month then date followed by an underscore the hour then minutes then seconds.
For the impatient out there here is the final code I use to get this date and time stamp:
I’ll explain why it looks more complicated than you (and I) might have thought it should be afterwards.
set /a hh=%hh%+100
The %Time% variable in a batch file will give you a time like 18:55:30.32
The %Date% variable will give you “Fri 02/11/2010″.
Since I’m using this to create file and folder names you can’t have slashes and colons etc. mixed in there.
So, being a VB programmer I started out thinking I could use something like the mid function to take the date and time apart and then put it back together in the string I wanted.
I found that you can take just a part of the %date% variable by doing the following: %date~10,4%
This takes the %date% variable starts at the first character after the 10th and grabs 4 characters.
Cool, so you end up %date~10,4% = 2011 (unless you go back in time to last year or forward to next year in which it will be something else and if you can do that then you probably aren’t reading this.)
You can add a negative sign before the first number and it will go from right to left instead of left to right when setting character position.
So with %date:~10,4%%date:~4,2%%date:~7,2% = 20110211 (because today is 02/11/2011).
Take the time and you get %time:~-11,2%%time:~3,2%%time:~6,2% = 191551 (because it’s 7:15 pm at 51 seconds)
Based on these then I came up with:
This returns: 20110211_191655 and was exactly what I wanted. So, why is the final code I gave you above so much more complicated? I started using the above code and had problems when it went to make a folder and the time was like 2 am.
The problem is the hour part of the %time% variable doesn’t return a two digit hour like at 2 am. The %time~-11,2% would return a 2 with a space before it breaking the whole thing.
So, the first lines in the above code compensates for this by taking the hour and adding 100 to it and then pulling out the last 2 characters of what remains. So at 2 am you end up with 102, take the last two characters and you get 02. This makes for a more reliable method of making folders and file names using the %date% and %time% variables.
There might be a much better, shorter way to accomplish this but I couldn’t find it so here’s the final code:
(until someone smarter than me tells me how silly I am for doing it this way and gives me something better)
set /a hh=%hh%+100