Getting date and time in desired format in DOS/Windows cmd prompt


If you are familiar with Linux's date command and its pretty output formatting, you'll be surprised by the lack of even tiny bit of formatting in its DOS/Windows equivalent. However there's workaround for this. To get _time variable set to the current time in format HHMMSSmm and _date to YYMMDD, use this code:
 
SETLOCAL
    for /f "tokens=1-3 delims=1234567890 " %%a in ("%time%") do set "delims=%%a%%b%%c"
    for /f "tokens=1-4 delims=%delims%" %%G in ("%time%") do (
        set _hh=%%G
        set _min=%%H
        set _ss=%%I
        set _ms=%%J
    )
    set _hh=%_hh: =%
    if 1%_hh% LSS 20 set _hh=0%_hh%
ENDLOCAL&set _time=%_hh%%_min%%_ss%%_ms%
SETLOCAL
   for /f "tokens=1-4 delims=/-. " %%G in ('date /t') do (call :s_fixdate %%G %%H %%I %%J)
   goto :s_end  
   :s_fixdate
   if "%1:~0,1%" GTR "9" shift
   for /f "skip=1 tokens=2-4 delims=(-)" %%G in ('echo.^|date') do (
       set %%G=%1&set %%H=%2&set %%I=%3)
   goto :eof
   :s_end
ENDLOCAL&set _date=%yy%%mm%%dd% 

Source: http://ss64.com/nt/syntax-getdate.html and http://ss64.com/nt/syntax-gettime.html

 

No comments yet

Back to articles list

This page was last modified on 2024-12-05 17:22:24