开发者

Day missing from Date

See Batch code below, it show a date and time but the day is missing. How to fix this?

code:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set dt=%%c-%%a-%%b)
For /f "tokens=1-4 delims=:." %%a in ('echo %time%') do (set tm=%%a.%%b)
set bkupfilename=%1 %dt% %tm%.bak
echo Backing up to开发者_运维知识库 file: %bkupfilename%

Output:

C:\wamp>backup.bat
Backing up to file:  -08-2011 15.49.bak


when parsing output of system commands like date /t, the system locale is very important.

the first line of the script issues the command date /t and parses its output. it splits the string at specified delimiters, which are the space (hence the space before the end ") and the slash /. it then takes the 2nd to 4th items found and assign them to variables %a, %b and %c.

if you type date /t on your console you will see the output and understand why the script is not working...

  • the system on which this command was written used american date format (month-day-year),
  • on my system, which uses european date format (day-month-year), the script works but invert the month and the day.

i suppose that on your system, the ouput of the date /t command is different, due to your system locale settings. you will have to modify your script in order to comply to these settings.

(also, keep in mind that this kind of script is not portable: another user using another locale will encounter the same kind of problems)


You are using delimiters that cut off the day on the first line (2-4).

To fix it just change the first line to have 1 as the start:

For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set dt=%%c-%%a-%%b)

Complete code:

@echo off
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set dt=%%c-%%a-%%b)
For /f "tokens=1-4 delims=:." %%a in ('echo %time%') do (set tm=%%a.%%b)
set bkupfilename=%1 %dt% %tm%.bak
echo Backing up to file: %bkupfilename%

Note: you can change it also to 1-3 as there is no need for 1-4 but it will work all the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜