Locale-unaware %DATE% and %TIME% in batch files?

There were a few attempts (Rob van der Woude had something), but nothing really worked across all locales. However, you can get the current time in a easily-parseable format via

wmic os get LocalDateTime

The following gets you at least UTC already:

@echo off
rem Get the time from WMI - at least that's a format we can work with
set X=
for /f "skip=1 delims=" %%x in ('wmic os get localdatetime') do if not defined X set X=%%x
echo.%X%

rem dissect into parts
set DATE.YEAR=%X:~0,4%
set DATE.MONTH=%X:~4,2%
set DATE.DAY=%X:~6,2%
set DATE.HOUR=%X:~8,2%
set DATE.MINUTE=%X:~10,2%
set DATE.SECOND=%X:~12,2%
set DATE.FRACTIONS=%X:~15,6%
set DATE.OFFSET=%X:~21,4%

echo %DATE.YEAR%-%DATE.MONTH%-%DATE.DAY% %DATE.HOUR%:%DATE.MINUTE%:%DATE.SECOND%.%DATE.FRACTIONS%

However, you probably need to account for the time zone offset (unless it's for a log file, then I'd always use UTC) but that's nothing a bit of calculation cannot do :-)


Here's a two-liner I've been using, which seems to work regardless of Windows version or local time settings:

FOR /f %%a in ('WMIC OS GET LocalDateTime ^| find "."') DO set DTS=%%a
set CUR_DATE=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%

This will set a variable called %CUR_DATE% in the following ISO standard format:

yyyy-mm-dd

I tried making it a one-liner with &&, but it didn't seem to take, so I resorted to the two-line version. Hope this helps.