比较批处理文件中的2个日期

时间:2013-03-27 22:21:43

标签: batch-file

我用它来修改文件的日期:

@echo off
FOR %%? IN ("C:\some.exe") DO (
    ECHO Last-Modified Date   : %%~t?
)

以上内容返回类似:Last-Modified Date:26/03/2013 14:43。

如何从上面获取日期部分并将其与另一个名称包含日期的文件进行比较,即:23-Sep-13.exe?

如果名称中包含日期的文件晚于文件修改版本,即安装更新,我需要能够在批处理文件中执行一些代码。

1 个答案:

答案 0 :(得分:1)

@ECHO OFF
SETLOCAL
:: No doubt for international use, this could be retrieved from the registry
SET monthnames=Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
:: get last modified date of target file - your format as specified
:: (I used THIS BATCH FILE)
FOR %%i IN ("%~f0") DO SET target=%%~ti
:: parse the target date
FOR /f "tokens=1-3delims=/ " %%i IN ("%target%") DO SET targetf=%%k%%j%%i
::
:: parse name from 'other file'
SET other=23-Sep-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
:: @ECHO on
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
::
:: parse name from 'another other file'
SET other=23-Jan-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.

代码将(此批次)的日期作为目标(您的'C:\some.exe' - 更改为适合。

测试然后应用于两个不同的filename-is-date+ext格式文件名进行测试。

如果需要与20世纪日期进行比较,可以轻松调整......:)