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
On a Microsoft Windows system, you can obtain the current date using the date /t command (the /t option prevents the command from prompting for a change to the the date) or by using echo %date% to display the contents of the date environment variable.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
doc or . txt extension in the current directory is substituted for the %f variable until the contents of every file are displayed. To use this command in a batch file, replace every occurrence of %f with %%f. Otherwise, the variable is ignored and an error message is displayed.
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%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With