How to compare date in Batch script

2019-09-05 14:44发布

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).

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.

How can I do this?

2条回答
Emotional °昔
2楼-- · 2019-09-05 15:22

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

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.

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.

查看更多
Explosion°爆炸
3楼-- · 2019-09-05 15:24

This method use a subroutine that allows you to compare two dates with any comparison of if command, like leq, gtr, etc.

@echo off

call :CompareDates 1/1/2015 equ 01/01/2015
if %errorlevel% equ 0 (
   echo Dates are equal
) else (
   echo Dates are different
)
goto :EOF


:CompareDates date1 comparison date2
for /F "tokens=1-6 delims=/" %%a in ("%1/%3") do (
   set /A m1=10%%a,d1=10%%b,y1=%%c, m2=10%%d,d2=10%%e,y2=%%f
)
if %y1%%m1:~-2%%d1:~-2% %2 %y2%%m2:~-2%%d2:~-2% exit /B 0
exit /B 1

This code assume that the date format is MM/DD/YYYY. If your date format is different, just change the m1,d1,m2,d2 variables in the set /A command with the proper order.

查看更多
登录 后发表回答