比较批处理文件中的2个日期 [英] Compare 2 dates in a batch file

查看:194
本文介绍了比较批处理文件中的2个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用它来获取文件的修改日期:

I am using this to get the date modified of a file:

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

上面返回的内容类似:Last-Modified Date:26/03/2013 14:43.

The above returns something like: Last-Modified Date : 26/03/2013 14:43.

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

How can I take the date part from the above and compare it against another file which's name contains a date ie: 23-Sep-13.exe?

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

I need to be able to perform some code in the batch file if the file that contains the date in its name is later than the file modified version ie install the update.

推荐答案

@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'-更改为适合.

Code takes date of (this batch) as the target (your 'C:\some.exe'- change to suit.

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

test then applied to two different filename-is-date+ext format filenames to test.

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

Can be easily adjusted if comparisons to 20th-Century date is required... :)

这篇关于比较批处理文件中的2个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆