Tuesday, October 20, 2009

Separating date and time variables in a Windows batch script

I know this is very old school, but I have, on occasion needed to perform date and time operations in a batch script and always have to re-figure it out. This code will separate out the numeric year, month, and day values and store them to their respective variables. The other line of will get the current weekday and store it in a variable as well (Sat, Sun, etc.). If it's not used in a script, remove the extra % in front of the variables.

for /f "tokens=1,2" %%a in ('date /t') do for /f "tokens=1,2,3 delims=/" %%i in ("%%b") do set YEAR=%%k& set MONTH=%%i& set DAY=%%j

for /f "tokens=1" %%a in ('date /t') do set WDAY=%%a