如何格式化批处理文件中的日期

时间:2018-04-16 14:24:28

标签: batch-file

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

此处mydate20180416。如何在此处以yymmdd格式获取日期?

1 个答案:

答案 0 :(得分:0)

对于特定于语言环境的方法,您只需添加一行,删除前两个字符:

@Echo Off
For /F "Tokens=2-4 Delims=/ " %%A In ('Date /T') Do Set "mydate=%%C%%A%%B"
Set "mydate=%mydate:~2%"
Echo [%mydate%]
Timeout -1

虽然对于那种格式你甚至可以做得更简单:

@Echo Off
Set mydate="%DATE:~-2%%DATE:~-10,2%%DATE:~-7,2%"
Echo [%mydate%]
Timeout -1

或者对于与语言环境无关的方法......

您可以使用RoboCopy

@Echo Off
For /F "Tokens=1-3 Delims=/ " %%A In ('RoboCopy/NJH /L "\|" Null'
) Do Set "mydate=%%A%%B%%C" & GoTo :Break
:Break
Set "mydate=%mydate:~2%"
Echo [%mydate%]
Timeout -1

WMIC

@Echo Off
For /F "EOL=L" %%A In ('WMIC OS Get LocalDateTime'
) Do Set "mydate=%%~nA" & GoTo :Break
:Break
Set "mydate=%mydate:~2,6%"
Echo [%mydate%]
Timeout -1

MakeCab

@Echo Off
Set "df=%TEMP%\~foo.ddf"&Set "tf=%TEMP%\~%RANDOM%"
Set /A "Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12"
(   Echo .Set InfHeader=""&Echo .Set InfSectionOrder=""&Echo .Set InfFooter="%%2"
    For /L %%A In (1 1 4) Do Echo .Set InfFooter%%A=""
    Echo .Set Cabinet="OFF"&Echo .Set Compress="OFF"&Echo .Set DoNotCopyFiles="ON"
    Echo .Set RptFileName="NUL")>"%df%"
MakeCab /D InfFileName="%tf%" /F "%df%">Nul
For /F "UseBackQ Tokens=2-3,5" %%A In ("%tf%") Do Set /A "mm=%%A,dd=10%%B,yyyy=%%C"
Del "%tf%" "%df%">Nul 2>&1&Set "mm=10%mm%"
Set "mydate=%yyyy:~-2%%mm:~-2%%dd:~2%"
Echo [%mydate%]
Timeout -1

甚至可以使用PowerShell

@Echo Off
For /F %%A In ('PowerShell "(Get-Date).ToString('yyMMdd')"') Do Set "mydate=%%A"
Echo [%mydate%]
Timeout -1