How do I compare timestamps of files in a batch script?

Viewed 85424

In DOS batch files, the method of achieving certain things is somewhat obfuscated. Fortunately, there is a fantastic reference site for batch scripting: Simon Sheppard's SS64. (The same site also has plenty of information about Bash.)

One difficulty is branching execution based on whether a directory is empty. The obvious if exist "%dir%\*.*" doesn't work. But it can be done with this conditional execution trick:

( dir /b /a "%dir%" | findstr . ) > nul && (
  echo %dir% non-empty
) || (
  echo %dir% empty
)

Another awkward problem is branching according to file contents. Again that can be done like this:

( fc /B "%file1%" "%file2%" | find "FC: no differences encountered" ) > nul && (
  echo "%file1%" and "%file2%" are the same
) || (
  echo "%file1%" and "%file2%" are different
)

So, my question is:
Is there a way to do branch according to the time-stamps of files?

This is the sort of thing I want:

REM *** pseudo-code!
if "%file1%" is_newer_than "%file2%" (
  echo "%file1%" is newer
) else if "%file1%" is_older_than "%file2%" (
  echo "%file2%" is newer
) else (
  echo "%file1%" and "%file2%" are the same age
)

Thanks.

8 Answers

I would use xcopy for this:

xcopy /L /D /Y PATH_TO_FILE1 PATH_TO_FILE2|findstr /B /C:"1 " && echo FILE1 is newer!

Because the xcopy always returns true in this case you need to filter its output with the findstr command.

  • The /L is for listing only, nothing is copied.
  • The /D is doing the time comparision. Hint: By swapping File1 and File2 you can decide how to handle identical files.
  • The /Y in only necessary to avoid an 'Overwrite existing' question.

That's all and it works with different paths.

The freeware command line program WASFILE (https://www.horstmuc.de/wbat32.htm#wasfile) will also do a file date/time comparison for you.

Here's the quick program writeup from the web page:

*WasFile compares ..
.. time&date of two files (or directories),
.. the date of two files, time ignored
.. the date of a file with today-n (days)
.. time&date of a file with now-n (minutes)
Examples:
WasFile this.zip created before that.zip
WasFile this.zip modified after today-8
WasFile this.dat created before now-10
Using file stamps for created, modified (default) or accessed;
comparison: [not] before|after|sametime
Option to compare date only, ignore time: /DateLocal or /DateUTC*
Related