Time & Date stamp for batch files

This has been driving me crazy – how to get a decent Time & Date stamp in a batch file. After much Googling and experimenting I came up with this. 

This was tested on XP Pro with English (United States) Regional Settings and will likely not work if your Regional Settings are different. Take a look at the comments from d_m_g_3 below for a Region (United Kingdom) version that does work.

If you’ve tried this and found a way to make it work with your Regional Settings, please leave a comment below with the Region & code you got working to save someone else the headache of figuring it out!

SET TimeStamp=
for /f "tokens=1-4 delims=/ " %%i in ("%date%") do set datestr=%%l%%j%%k
for /f "tokens=1-4 delims=.: " %%i in ("%time%") do set timestr=%%i%%j%%k%%l
SET TimeStamp=%datestr%%timestr%

It sets the environment variable TimeStamp to the format YYYYMMDDHHMMSSmm.

As soon as I can back track to where I got the bulk of this, I’ll post appropriate credit.

02/19/2012 Update:

I found another approach at Print Date/Time in DOS Batch File that works well for me most of the time, but does have an issue with using a leading space for single digit hours. DOS’s ReName has a problem with that so I’ve settled on just using the DATESTAMP variable – it’s close enough for most of my needs.

Create a date and time stamp in your batch files uses a slightly different approach with SUBSTRING to extract the parts and also explains how to use TRIM to get around the leading space problem.

5 Responses to “Time & Date stamp for batch files”

  1. Not on my system (Windows XP ENU)

    TimeStamp=04200915113962

    The current date time is 08 April 2009 15:11

    I think maybe your solution only works for your Regional Settings?

  2. For my region (United Kingdom), the following works

    SET TimeStamp=
    for /f “tokens=1-3 delims=/” %%a in (‘echo %date%’) do SET DATESTR=%%c%%b%%a
    for /f “tokens=1-4 delims=:.” %%a in (‘echo %time%’) do SET TIMESTR=%%a%%b%%c%%d
    SET TimeStamp=%datestr%%timestr%

  3. @d_m_g_3 Thanks for testing & pointing this out! I’m in the US & using English (United States) as my region, but taking a quick glance at a few different formats in the Regional Settings, I can see where my script could easily fail.

    I’ll update the post to point out that it’s based on US regional settings.

    Eric

  4. great – thank you -works for me (USA) and saved me lots of time. linux is so much easier with this kind of stuff

  5. You can use :~ within the date and time variables much easier.

    See http://www.intelliadmin.com/index.php/2007/02/create-a-date-and-time-stamp-in-your-batch-files/

    It might work with regional settings. As always, test.

Leave a Reply