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%

Leave a Comment