* Create your FREE website now *

Date and Time

Tags:  

In a lot of scripts you need a quick way to format dates and times.

date /t gives output in a painful format like Tue 10/16/2007  ... the below munges that into a sort-able ISO-ish date in format 2007-10-16. NOTE that this uses the single-% style appropriate to interactive cmd sessions; for batchfiles, use double %% as seen in the other scripts on this page.


for /f "tokens=1-4 delims=/ " %a in ('date /t') do echo %d-%b-%c

C:\>for /f "tokens=1-4 delims=/ " %a in ('date /t') do echo %d-%b-%c
2007-10-16

C:\>

time /t isn't so bad, outputting as 05:53 PM. But it can be nice to have a 24-hour time format, like 17:53 ... the script below does that.


  1. @echo off
  2. setlocal
  3. for /f "tokens=1-3 delims=: " %%a in ('time /t') do (
  4.  set hours=%%a
  5.  set minutes=%%b
  6.  set ampm=%%c
  7. if {%ampm%}=={AM} if {%hours%}=={12} set hours=00
  8. if {%ampm%}=={PM} (
  9.  for /f "delims=0 tokens=*" %%a in ("%hours%") do set hours=%%a
  10.  set /a hours+= 12
  11. )
  12. if {%hours%}=={24} set hours=00
  13. echo %hours%:%minutes%
  14. endlocal

You may be wondering about line #10. If it's 9:02 PM, the time command returns 09:02 PM. The problem with this is that we end up with "09" as the %hours% variable. We have to strip out the leading zero, because if we do not, the set /a statement in line 11 will think '09' is an octal number and refuse to properly add 12 + 09(octal). So I use the for statement in line 10 to  tokenize the variable, using zero as a delimiter, thus removing the leading zero.

Also, notice the setlocal and endlocal statements at line 2 and line 15. These keep all of our variables local. Once the script ends, the %hours%, %minutes%, and all other variables will be flushed. They basically disappear after the script completes.

If the above script were saved as 24time.cmd, it would echo something like:

C:\>24time
22:15

C:\>

We can easily put date and time together as a single script that would produce the current date/time as a string like 2007-10-16 17:53 ... line 3 is added, and line 15 is changed slightly, to make this happen.


  1. @echo off
  2. setlocal
  3. for /f "tokens=1-4 delims=/ " %%a in ('date /t') do set ISODATE=%%d-%%b-%%c
  4. for /f "tokens=1-3 delims=: " %%a in ('time /t') do (
  5.  set hours=%%a
  6.  set minutes=%%b
  7.  set ampm=%%c
  8. if {%ampm%}=={AM} if {%hours%}=={12} set hours=00
  9. if {%ampm%}=={PM} (
  10.  for /f "delims=0 tokens=*" %%a in ("%hours%") do set hours=%%a
  11.  set /a hours+= 12
  12. )
  13. if {%hours%}=={24} set hours=00
  14. echo %ISODATE% %hours%:%minutes%
  15. endlocal


Here's what the output of the above would look like, if it were saved as isodate.cmd

C:\>isodate
2007-11-26 22:15

 C:\>


0 Comments
Post a comment



 RSS of this page

Written by:   Written by:   Version:   Last Edited By:   Modified