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 only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file
Wscript.Echo("set Year=" & DatePart("yyyy", Date))
Wscript.Echo("set Month=" & DatePart("m", Date))
Wscript.Echo("set Day=" & DatePart("d", Date))
and this batch snippet
for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
echo %Year%-%Month%-%Day%
should work, though.
While you can get the current date in a batch file with either date /t
or the %date%
pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.
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.
A variant of script that works local-independently. Put it in a text file with .cmd extension and run.
::: Begin set date
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)
goto :end_set_date
:set_date
if "%1:~0,1%" gtr "9" shift
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)
goto :eof
:end_set_date
::: End set date
echo day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%
The variables %dd%, %mm% and %yy% will keep the day('DD' format), the month('MM' format) and the year('YYYY' format) respectively.