I would like to offer a variation to the excellent GetDate.cmd answer of Tex Hex, and use the wmic parameter "/format:list" instead, to assign the values straight away to batch variables, as demonstrated below. To add the leading zeroes, I used another FOR loop, instead of dealing with each variable individually. It's not much shorter (in total bytes) nor faster, simply a different way of doing it:
@ECHO OFF
REM Defines variables _Year (4 digits), _Month (01-12), _Day (01-31), _DayOfWeek (0=Sun, 1=Mon etc), _Hour (00-23), _Minute (00-59), _Second (00-59)
setlocal EnableDelayedExpansion
FOR /F %%I IN ('WMIC path win32_localtime get Year^,Month^,Day^,DayOfWeek^,Hour^,Minute^,Second /format:list^|FINDSTR "="') DO SET _%%I
FOR /F "tokens=1 delims==" %%I IN ('set _^|FINDSTR /R "^_[DHMS][aoie][^k]*$"') DO SET %%I=0!%%I!&SET %%I=!%%I:~-3!
:: Display the date/time and day of week
ECHO %_Year%-%_Month%-%_Day% %_Hour%:%_Minute%:%_Second% (day %_DayOfWeek%)
::if this script is called from another script, 'endlocal' will be assumed and our variables will be gone. So use a trick to retain them:
set _>%TEMP%\%~n0.tmp
endlocal&(FOR /F %%I IN (%TEMP%\%~n0.tmp) DO SET %%I)&del %TEMP%\%~n0.tmp
I included DayOfWeek, in case someone needs it too.
Note: If this script is called from another batch script, endlocal
would be assumed at the end of this one, and our variables _Year etc. would be gone. Therefore we cannot ommit endlocal
, and need to use a trick to keep the variables that we have defined. I thought it could be done easily, using endlocal& FOR /F %%I IN ('set _') DO SET %%I
, but that does not work, says variable _ is not defined... For that reason I resorted to a temporary file instead.
Furthermore, since the calling script might also be using variable names starting with an underscore, I included a check that the variables whose values I am altering start with a certain capital followed by a certain lower case letter. (Batch variable names are not case sensitive, but FINDSTR by default is.) So if your script is using variable names starting with underscores, make sure they are all lower case (or all upper case) and everything will be fine.