Windows batch: formatted date into variable
You can get the current date in a locale-agnostic way using
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
Then you can extract the individual parts using substrings:
set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%
Another way, where you get variables that contain the individual parts, would be:
for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%
Much nicer than fiddling with substrings, at the expense of polluting your variable namespace.
If you need UTC instead of local time, the command is more or less the same:
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%
If you wish to achieve this using standard MS-DOS commands in a batch file then you could use:
FOR /F "TOKENS=1 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET dd=%%A
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2,3 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET yyyy=%%C
I'm sure this can be improved upon further but this gives the date into 3 variables for Day (dd), Month (mm) and Year (yyyy). You can then use these later in your batch script as required.
SET todaysdate=%yyyy%%mm%%dd%
echo %dd%
echo %mm%
echo %yyyy%
echo %todaysdate%
While I understand an answer has been accepted for this question this alternative method may be appreciated by many looking to achieve this without using the WMI console, so I hope it adds some value to this question.
Use date /T
to find the format on command prompt.
If the date format is Thu 17/03/2016
use like this:
set datestr=%date:~10,4%-%date:~7,2%-%date:~4,2%
echo %datestr%