2

I've created a timestamp variable in a batch script like so...

set TIMESTAMP=%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%-%TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%

There is an issue though when the HH is only a single digit I get...

YYYY-MM-DD- 2-MM-SS

instead of

YYYY-MM-DD-02-MM-SS

How do I consistently generate the timestamp without spaces?

ѺȐeallү
  • 2,887
  • 3
  • 22
  • 34
  • 1
    Closely related: [How do I get current datetime on the Windows command line, in a suitable format for using in a filename?](https://stackoverflow.com/q/203090) – aschipfl Aug 02 '17 at 17:44

2 Answers2

3
set "timestamp=%timestamp: =0%"

replaces spaces with zeroes.

See set /? from the prompt for documentation.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • I can agree that this works if the current locale setting is just right. However, it still leaves the result as a locale specific format. @LotPings answer is locale independent. It works everywhere. – lit Aug 02 '17 at 18:40
2

Don't use locale/user settings dependent date time variables but wmic:

@Echo off
For /f "delims=." %%A in (
  'wmic os get LocalDateTime^|findstr ^^20'
) Do Set DT=%%A
Set "TIMESTAMP=%DT:~0,4%-%DT:~4,2%-%DT:~6,2%-%DT:~8,2%-%DT:~10,2%-%DT:~12,2%"
Set TimeStamp

Sample output:

> SO_45465890.cmd
TIMESTAMP=2017-08-02-18-42-07

Or use PowerShell and let it do the formatting:

@Echo off
For /f %%A in ('powershell -NoP -C "get-date -f \"yyyy-MM-dd-HH-mm-ss\""') Do Set TimeStamp=%%A
Set TimeStamp