views:

125

answers:

3

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.

A: 

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.

Joey
Alright...sounds good, but are these VBScript methods in scope in the cmd shell? Do I have to install a library and reference it in the script?
Mossen
`cscript` is the console interpreter for the Windows Script Host. It exists since Windows 98 in the default installation of any Windows (except maybe Server Core). However, if possible I tend to avoid VBScript since the WSH can be disabled via group policies. Something that cannot be done with batch files. But in this specific case it's just painful with pure batch.
Joey
+1  A: 

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.

poke
+1  A: 

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.

Andrei Coscodan