Batch file day/month/year syntax?

2019-06-21 21:02发布

问题:

I can't find a simple breakdown of the batch file syntax for extracting the current day/month/year.

I have the following syntax for declaring a variable used as a directory name;

set folder=%date:~10,4%%date:~7,2%%date:~4,2%

Can anyone shed some light (or post a link) on what the tilde, the double percentage means? I can't seem to fully decipher it from intuition alone.

回答1:

The double percentage means absolutely nothing. It is simply a result of having two variable expansions side-by-side such as:

echo %firstname%%lastname%
     \_________/\________/
      Two separate expansions.

The tilde gives you a substring. In your case, %date:~10,4% gives you four characters at offset ten of the date environment variable (the year in this case since the format is likely Thu 29/12/2011, with offsets starting at zero).

If you enter set /? at a Windows command pronpt, it will explain all the options for you, including the nifty trick of using negative offsets to extract from the end of the string.

However, you should keep in mind that the date environment variable format depends on the locale so this simplistic string extraction is unlikely to work across all international versions of Windows (this bit me a couple of years back).

A better solution is to use WMI to get the date components such as on Rob van der Woude's excellent scripting pages, copied here for completeness:

FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Dayˆ,Hourˆ,Minuteˆ,Monthˆ,Secondˆ,Year /Format:table') DO (
    IF NOT "%%~F"=="" (
        SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
        SET /A SortTime = 10000 * %%B + 100 * %%C + %%E
        SET SortTime=0000000!SortTime!
        SET SortTime=!SortTime:~-6!
    )
)


回答2:

The ~ and %%s are splitting the string (if you just type date into command it shows you the full string).

%date:~10,4% means get next 4 characters from the 10th character along.

Also watch out for different PCs using different Regional Settings, as they change the order of those characters in the string.



回答3:

@paxdiablo beat me to it. Here's a link to a site that explains how it works, with plenty of examples.