Dangerous Things
Custom gadgetry for the discerning hacker

The Store is now open! Check out the gadgetry »
Like what you're reading?
Share It.

How to properly get date / time in a batch file

This is something that I should have posted a long time ago. Sadly though, with things like PowerShell out now, old school batch files are quickly becoming extinct, even for hardened batchers like myself. However I still find myself using batch files of some sort from time to time, and often times I need to utilize the date in some form or another… either to make a decision, to store and pass in an environment variable, or to use to format a file name. I’m sure there are plenty of admins out there that do the same, hence this post.

Unfortunately, something I see constantly are all kinds of crazy solutions for getting the system date and time in a batch file. Some involve 3rd party utilities, while others involve filtering and dumping date/time data to sub-batch files, etc. However, the best, cleanest way to get the system date and time is to use the built-in data parsing functions that the DOS emulator has had since at least Windows 2000.

The syntax looks like this %date:~S,L% where S is starting character position of date substring and L is the substring length. This syntax can be dumped into an environment variable, or used directly in file names. For example, you could use “%date:~10,4%-%date:~4,2%-%date:~7,2%_backup.zip” in a daily batch file to generate backup targets with “yyyy-mm-dd_backup.zip” formatted file names.

Simple, right?

Another fun trick is getting the path of the batch file currently running; echo %~dp0


3 Responses to “How to properly get date / time in a batch file”

  1. Great article. Thank a lot

  2. troy says:

    what if I had three files being created on a daily basis like this –

    I need to make sure they are created on a daily basis with that day’s date and time stamp.

    The Year-Month-Day format on the end of the file will always be in these positions.

    Any suggestions on how to setup a bat file to check this and send an email to me ?

  3. Amal says:

    Hi Troy,

    As shown in the post – %date:~10,4%-%date:~4,2%-%date:~7,2%_backup.zip will create a file named YYYY-MM-DD_backup.zip

    You simply need to move the code around: Online_Litters_%date:~10,4%-%date:~4,2%-%date:~7,2%.txt

    %date:~10,4% = year
    %date:~4,2% = month
    %date:~7,2% = day

    Simply insert these into your file directives and you’ll have your year, month, and day.

Leave a Reply

Get Adobe Flash player