Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a modified file date with the current date in a batch file

I'm required to write a batch file to do a few things

Initially I thought my problem was very simple - capture the modified date of a txt file located in a specified directory, compare that date to the current date and if they are the same do something. If they are not then do something else.

The line I use to capture the current date is:

%date%

The lines I use to capture the modified date of my specified file is:

SET filename="C:\New Folder\New.txt"
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
ECHO %filedatetime:~0,-6% >> %destination%

In the above case I'm simply using echo to see what is returned and it seems as if the date is returned but I get extra information:

2012/02/19 02

I would like to know how to get the above values where they are comparable as well as how to compare them properly.

like image 418
Kalim Avatar asked Feb 19 '12 13:02

Kalim


2 Answers

Working with dates is much harder in batch then it ought to be.

There is one command that can make your job easy in this case. FORFILES has the ability to process files that have been modified since a particular date. Use FORFILES /? from the command line to get documentation on its use.

This simple command will list all files that have been modified today:

forfiles /m * /d 0

If at least one file is found, then ERRORLEVEL is set to 0, else ERRORLEVEL is set to 1.

You have a specific file, so you can use

forfiles /m %filename% /d 0
if %errorlevel% == 0 (
  echo The file was modified today
  REM do whatever else you need to do
) else (
  echo The file has not been modified today
  REM do whatever else you need to do
)

There is a more concise way to do the above. The && operator is used to conditionally execute commands if the prior command was successful, || is used to conditionally execute commands if the prior command failed. However, be careful, the || commands will also execute if the && command(s) failed.

forfiles /m %filename% /d 0 && (
  echo The file was modified today
  REM do whatever else you need to do
) || (
  echo The file has not been modified today
  REM do whatever else you need to do
)
like image 194
dbenham Avatar answered Oct 09 '22 17:10

dbenham


I like dbenham's way, but if you want to make your code work you can do like this:

set currentDate=%date%
SET filename="C:\MyFile.txt"

FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
IF %filedatetime:~0, 10% == %currentDate% goto same

goto notsame

:same
echo Dates the same, do some code here

goto next

:notsame
echo Dates NOT the same, do some code here
goto end

:next

Thought it would be worth knowing how to make yours work just in case you need it again.

like image 27
SmithMart Avatar answered Oct 09 '22 19:10

SmithMart