0

In a Windows batch file, is it possible to get the text of date in some location independent form to get the location independent date stamp as a string? To make the question clear... In the Czech Windows, the wanted code looks like this:

d:\>date /t
čt 16. 05. 2019

d:\>echo %DATE:~-4%%DATE:~-8,2%%DATE:~-12,2%
20190516

However, in the English Windows the same code returns bad results for obvious reasons:

d:\>date /t
Thu 05/16/2019

d:\>echo %DATE:~-4%%DATE:~-8,2%%DATE:~-12,2%
2019/1u

If the code is tuned for the English Windows, then it does not work in the Czech environment. How it should be implemented?

pepr
  • 19,048
  • 14
  • 71
  • 132

1 Answers1

3

Here is a method you can manipulate the output of wmic os get LocalDateTime /VALUE

@echo off
for /f "tokens=1,2 delims==" %%i in ('wmic os get LocalDateTime /VALUE 2^>nul') do (
    if ".%%i."==".LocalDateTime." set mydate=%%j
)
set mydate=%mydate:~0,4%/%mydate:~4,2%/%mydate:~6,2% %mydate:~8,2%:%mydate:~10,2%:%mydate:~12,6%
echo %mydate%

and in the specific format you seem to want it YYYYMMDD and excluding time:

@echo off
for /f "tokens=1,2 delims==" %%i in ('wmic os get LocalDateTime /VALUE 2^>nul') do (
    if ".%%i."==".LocalDateTime." set mydate=%%j
)
set mydate=%mydate:~0,4%%mydate:~4,2%%mydate:~6,2%
echo %mydate%
Gerhard
  • 21,163
  • 7
  • 24
  • 41
  • This method works really well, but I have a small improvement for the variation that gets the format `YYYYMMDD`: one can also use `set mydate=%mydate:~0,8%` in line 5. Also I had to remove the `^>nul` in the for-command. – Daniel Fuchs Jan 14 '22 at 11:40
  • 1
    @DanielFuchs, cool, thanks. I made a mistake there, only stderr was supposed to be redirected to `nul` The second piece of code was a copy from the first, so kept the format, though `set mydate=%mydate:~0,8%` is shorter, yes. – Gerhard Jan 14 '22 at 12:16