批处理 - 将文件日期与实际日期进行比较

Batch - Compare file date with actual date

我从文件中得到 file date

for %%x in (%file_test%) do set file_date_test=%%~tx

然后我得到 system date:

set year=%date:~-4%
set month=%date:~3,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%

然后 if statementgoto:

IF %file_date_test% LSS %system_date_test% goto SOME

如何比较两个日期?我想检查文件日期是否 超过 24H.

哪种方法最好?我可以使用 forfiles 来做吗?

Edited forfiles 命令甚至不会查看文件的时间,因此之前的答案(在底部以防有人觉得有用)不会如果文件有不同的日期但少于 24 小时,则工作。

替代方案

robocopy "c:\backup" "c:\backup" "test.bak" /l /nocopy /is /minage:1 > nul 
if errorlevel 1 (
    echo MATCH
) else (
    echo NO_MATCH
)

至少在 windows 7 中,robocopy 命令查看文件的时间戳以确定其年龄。


上一个回答

您可以使用forfiles检查操作的错误级别

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "file_test=c:\backups\test.bak"

    for %%a in ("%file_test%") do (
        forfiles /p "%%~dpa." /m "%%~nxa" /d -1 >nul 2>nul && echo MATCH || echo NO MATCH
    )

@echo off
    setlocal enableextensions disabledelayedexpansion

    forfiles /p "c:\backups" /m "test.bak" /d -1 >nul 2>nul
    if errorlevel 1 (
        echo NO_MATCH
    ) else (
        echo MATCH
    )