Windows batch: formatted date into variable

How do I save the current date in YYYY-MM-DD format into some variable in a Windows .bat file?

Unix shell analogue:

today=`date +%F`
echo $today

Solution 1:

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%

Solution 2:

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%