简体   繁体   中英

MS-DOS timestamp in filename

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.

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

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.

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.

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM