How to append a datetime with a zero-padded hour in batch files

  batch-file, command-line, date, time, windows

I cannot figure out how to echo the date and time, with a zero padded hour, to insert a timestamp in my batch files.

The following is the set command that I use to echo the date and time:

set _DateTime=%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%-%time:~3,2%
echo _DateTime=%_DateTime% 

The following is what the code above generated in the console window at 9:50 AM:

C:>set _DateTime=2021-07-27_ 9-50
C:>echo _DateTime=2021-07-27_ 9-50
_DateTime=2021-07-27_ 9-50

As you can see, the hour is not zero padded.
There is a blank space, instead of a zero, preceding the 9.

I would like to know how to zero pad the hour, and where I can learn why your solution works.

Any suggestions about how to find the answer would be very welcome.

Thanks,
Marc

Source: Windows Questions

LEAVE A COMMENT