How do I get the current day month and year from inside a Windows cmd script? I need to get each value into a separate variable.
The following batch code returns the components of the current date in a locale-independent manner and stores day, month and year in the variables CurrDay, CurrMonth and CurrYear, respectively:
for /F "skip=1 delims=" %%F in ('
wmic PATH Win32_LocalTime GET Day^,Month^,Year /FORMAT:TABLE
') do (
for /F "tokens=1-3" %%L in ("%%F") do (
set CurrDay=0%%L
set CurrMonth=0%%M
set CurrYear=%%N
)
)
set CurrDay=%CurrDay:~-2%
set CurrMonth=%CurrMonth:~-2%
echo Current day : %CurrDay%
echo Current month: %CurrMonth%
echo Current year :%CurrYear%
There are two nested for /F loops to work around an issue with the wmic command, whose output is in unicode format; using a single loop results in additional carriage-return characters which impacts proper variable expansion.
Since day and month may also consist of a single digit only, I prepended a leading zero 0 in the loop construct. Afterwards, the values are trimmed to always consist of two digits.