Nothing and Everything

2010.11.04

Timestamps for Windows batch scripts

Filed under: Programming — kevenker @ 7:09 am

Just a quick snippet of code for Windows batch scripts. I had to fool around for a while to get this working so I figured I’d post it here so I wouldn’t forget it. And maybe somebody else would find it useful as well.

I wanted to generate a timestamp for naming files of the form yyyymmddhhmmss. The problem is that batch scripts don’t really support string formatting. You can get %date%, e.g. Thu 11/04/2010, and you can get %time%, e.g.  7:55:31.23. So you have to tease out the pieces manually, by using batch script’s “substring” abilities.

The only real “gotcha” is that the time doesn’t print a zero at the front of single digit times. So if you do something like:

set timestamp==%date:~-4%%date:~4,2%%date:~7,2%=%time:~0,2%%time:~3,2%%time:~6,2%

you can end up with a string that looks like: “20101104 75531″, with that space in it, which is rather annoying. Not to mention that it breaks scripts unless you put quotes around everything.

Basically, you need to check to see if the first character in the time portion is a space and if it is, insert a 0 at the front and grab everything after the space. So the snippet I developed is:


set datepart=%date:~-4%%date:~4,2%%date:~7,2%
set timepart=%time:~0,2%%time:~3,2%%time:~6,2%

if "%timepart:~0,1%"==" " set timepart=0%timepart:~1%
set timestamp=%datepart%%timepart%

PS – Sorry about the jacked up formatting. It seems WordPress is going through one of its periodic episodes where the editor decides to to whatever it feels like. The HTML mode no longer appears to actually let you edit HTML either, making things extra fun!!

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.