Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch: formatted date into variable

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 
like image 620
Maksym Polshcha Avatar asked Jun 08 '12 08:06

Maksym Polshcha


People also ask

How do I echo date in CMD?

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.

Why is %% used in batch file?

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.

What is %% f in batch file?

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.


1 Answers

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% 
like image 59
Joey Avatar answered Oct 18 '22 00:10

Joey