How do I get the day month and year from a Windows cmd.exe script?
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.
To get the year, month, and day you can use the %date%
environment variable and the :~
operator. %date%
expands to something like Thu 08/12/2010 and :~
allows you to pick up specific characters out of a variable:
set year=%date:~10,4%
set month=%date:~4,2%
set day=%date:~7,2%
set filename=%year%_%month%_%day%
Use %time%
in similar fashion to get what you need from the current time.
set /?
will give you more information on using special operators with variables.