1

I have the following in a batch file.

set timefmt=%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%

dir *.* > logfile_%timefmt%.log

This works perfectly after 10am, but fails before hand because it adds a space to the timestamp instead of a leading 0.

Is there a way in MS-DOS to create a time stamp with a leading 0? I'd prefer to use fairly standard commands so that it works from Windows XP onward.

ChrisGuest
  • 3,398
  • 4
  • 32
  • 53

4 Answers4

8

It's best to get the time once and then parse the elements, too. The third line will replace a space with a 0

set timefmt=%time%
set timefmt=%TIMEFMT:~0,2%%TIMEFMT:~3,2%%TIMEFMT:~6,2%
set timefmt=%TIMEFMT: =0%
dir *.* > logfile_%timefmt%.log
foxidrive
  • 40,353
  • 10
  • 53
  • 68
  • Point noted about grabbing the time first before doing string manipulation. That is best practice in all languages. – ChrisGuest May 22 '13 at 00:23
1

I had this problem too, but I have computers with different locale (some show yyyy-mm-dd for the date, some mm/dd/yyyy). Some show 12-hour clock with AM and PM, others 24-hour clock...

...so I ended up putting together a tool for saving the current date/timestamp in an environment variable. Actually, the tool just prints out the timestamp, but there is an example of how to get it into an environment variable:

for /f %%x in ('@timestamp.exe') do set TIMESTAMP=%%x

...and then you just use %TIMESTAMP% in any way you want.

Harry Pehkonen
  • 3,038
  • 2
  • 17
  • 19
1

Creating a file name as a timestamp in a batch job has quite a few answers to a problem close to this one. I insert this remark here because Google brought this answer first so that users who are in a hurry might miss the other thread.

Community
  • 1
  • 1
davitof
  • 161
  • 2
  • 6
1

I had that problem too.
so I did this. this got me over the hurdle.

:STEP_DATESTAMP
::
REM Setting Datestamp to YYYYMMDD
set v_datestampYYYY=%date:~6,4%
set v_datestampMM=%date:~3,2%
set v_datestampDD=%date:~0,2%
set v_datestamp=%v_datestampYYYY%%v_datestampMM%%v_datestampDD%
::
REM Setting Timestamp to HHMMSS
set HH=%time:~0,2%
:: ensure that hour is always 2 digits
if %HH%==0 set HH=00
if %HH%==1 set HH=01
if %HH%==2 set HH=02
if %HH%==3 set HH=03
if %HH%==4 set HH=04
if %HH%==5 set HH=05
if %HH%==6 set HH=06
if %HH%==7 set HH=07
if %HH%==8 set HH=08
if %HH%==9 set HH=09
set MM=%time:~3,2%
set SS=%time:~6,2%
set v_timestamp=%HH%-%MM%-%SS%

curtis
  • 11
  • 2