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.
-
@echo off
-
setlocal
-
for /f "tokens=1-3 delims=: " %%a in ('time /t') do (
-
set hours=%%a
-
set minutes=%%b
-
set ampm=%%c
-
)
-
if {%ampm%}=={AM} if {%hours%}=={12} set hours=00
-
if {%ampm%}=={PM} (
-
for /f "delims=0 tokens=*" %%a in ("%hours%") do set hours=%%a
-
set /a hours+= 12
-
)
-
if {%hours%}=={24} set hours=00
-
echo %hours%:%minutes%
-
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:
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.
-
@echo off
-
setlocal
-
for /f "tokens=1-4 delims=/ " %%a in ('date /t') do set ISODATE=%%d-%%b-%%c
-
for /f "tokens=1-3 delims=: " %%a in ('time /t') do (
-
set hours=%%a
-
set minutes=%%b
-
set ampm=%%c
-
)
-
if {%ampm%}=={AM} if {%hours%}=={12} set hours=00
-
if {%ampm%}=={PM} (
-
for /f "delims=0 tokens=*" %%a in ("%hours%") do set hours=%%a
-
set /a hours+= 12
-
)
-
if {%hours%}=={24} set hours=00
-
echo %ISODATE% %hours%:%minutes%
-
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:\> |