user1052610
user1052610

Reputation: 4719

Windows Batch: error message when getting date

I have the following batch file:

SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('!date! !time!) do echo %%c-%%a-%%b %%d %%e 
ENDLOCAL

I want to simply echo the current date. Instead, this message is output to the console:

The system cannot find the file 'Mon 06/29/2015 10:07:48.90.

What is wrong? Thanks

Upvotes: 0

Views: 108

Answers (1)

JosefZ
JosefZ

Reputation: 30268

SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
for /f "tokens=2-6 delims=:/ " %%a in ("!date! !time!") do echo %%c-%%a-%%b %%d %%e 
ENDLOCAL

However, your script depends on Windows locale; for instance, in my locale should be:

SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
for /f "tokens=1-5 delims=:. " %%a in ("!date! !time!") do echo %%c-%%b-%%a %%d %%e 
ENDLOCAL

Consider locale independent solution based on next code snippet:

for /F %%g in ('
  wmic OS get LocalDateTime /value^|findstr "="
  ') do for /F %%G in ("%%g") do echo set "_%%G"

Returns CIM_DATETIME format:

set "_LocalDateTime=20150629093247.246000+120"
::                  yyyymmddHHMMSS.mmmmmmsUUU

Replace ... do echo set "_%%G" with ... do set "_%%G" no sooner than debugged. Then next code snippet displays 2015-06-29 09 59:

SETLOCAL enableextensions enabledelayedexpansion
for /F %%g in ('
  wmic OS get LocalDateTime /value^|findstr "="
  ') do for /F %%G in ("%%g") do set "_%%G"
  echo !_LocalDateTime:~0,4!-!_LocalDateTime:~4,2!-!_LocalDateTime:~6,2! !_LocalDateTime:~8,2! !_LocalDateTime:~10,2!

Upvotes: 1

Related Questions