Use this batch file for YYYY-MM-DD format. It uses the window instrumentation tool that should be present in all recent Windows versions to get a datetime string which is independent of regional settings.
Save to a batch file into the path (eg) c:\windows\rdate.bat then access with a CALL RDATE.BAT to set the variable(s). Alternately, copy the code into your batch file.
This date format is suitable for filenames and logging. It sorts correctly. The logtime variable adds a date+time variable as YYYY-MM-DD-HHMMSS suitable for use in logging batch file activity at second accuracy.
Adjust the date (and time) formats as you wish. REM the screen echos in production. The two numbers in each text selection are the zero-based start character index and the number of characters to copy, eg, %datetime:~0,4% takes a 4 character substring starting at position 0.
echo off
rem First, get the locality-invariant datetime
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
rem echo %datetime%
rem Build the reverse date string YYYY-MM-DD
set rdate=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2%
echo rdate=%rdate%
rem Built a datetime string YYYY-MM-DD-hhmmss
set logtime=%rdate%-%datetime:~8,6%
echo logtime=%logtime%
replacing %date% by %date:~6,4%-%date:~3,2%-%date:~0,2% worked – MagTun – 2015-11-27T10:06:28.337
1Are you absolutely restricted to Batch? Such a thing is much simpler in VBScript/WSH and/or PowerShell ... – Adrien – 2011-07-27T23:20:54.350
@Adrien, Yes limited to batch - it's part of the VS2008 post-build step. – AngryHacker – 2011-07-28T00:06:15.527