如何在批处理脚本中比较日期 [英] How to compare date in Batch script

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

问题描述

我有一个包含日期的文本文件(格式类似于2015年1月1日或2015年1月1日...两种格式都可以接受).

I have a text file which contains a date (the format would be like 1/1/2015 or 01/01/2015... both formats are acceptable).

现在,我必须编写一个批处理脚本来比较日期.它必须表明日期1/1/2015和01/01/2015是相同的.

Now I have to write a batch script which will compare dates. It has to show that the dates 1/1/2015 and 01/01/2015 are the same.

我该怎么做?

推荐答案

这可能不是最优雅的方法,但是为了让您得到一个有效的样本-这将执行您需要的比较:

This is likely not the most elegant way, but in the interest of getting you a working sample - this performs the comparison you need:

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

REM Dates to compare.
REM Change the values here to test the results.
SET Date1=1/8/2015
SET Date2=01/08/2015

REM Break apart by slashes.
FOR /F "tokens=1-3 delims=/" %%A IN ("%Date1%") DO (
    SET Month1=00%%A
    SET Day1=00%%B
    SET Year1=20%%C

    REM Pad by taking the last chars from the right.
    SET Month1=!Month1:~-2!
    SET Day1=!Day1:~-2!
    SET Year1=!Year1:~-4!
)
FOR /F "tokens=1-3 delims=/" %%A IN ("%Date2%") DO (
    SET Month2=00%%A
    SET Day2=00%%B
    SET Year2=20%%C

    SET Month2=!Month2:~-2!
    SET Day2=!Day2:~-2!
    SET Year2=!Year2:~-4!
)

REM Perform comparisions.
IF /I "%Month1%" NEQ "%Month2%" GOTO NoMatch
IF /I "%Day1%" NEQ "%Day2%" GOTO NoMatch
IF /I "%Year1%" NEQ "%Year2%" GOTO NoMatch

REM If we get here, a match was found.
ECHO The dates are the same.
GOTO :EOF

:NoMatch
ECHO The dates are different.

ENDLOCAL

该示例可以轻松地用作子例程,该子例程将Date1Date2作为变量,然后设置一个返回变量以供主程序使用.

This sample could easily be used as a subroutine which takes in Date1 and Date2 as variables and then sets a return variable for use in the main program.

请注意,就脚本而言,月或日的顺序无关紧要.可以很容易地将Month1命名为Date1Part1(等),并且脚本可以正常工作.

Note that the order of month or day doesn't matter as far as the script is concerned. Month1 could just as easily be named Date1Part1 (etc.) and the script would work just fine.

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

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