Nov 23, 2013

Compare modified time of two files on DOS batch file.

I made a little complex but useful batch function for comparing the modified timestamp of two files. It is DOS batch command. BTW there is no command that does this on batch command without help of any external utilities.

The way it works is get DIR result and parse date/time info. I convert year/month/day/hour/min into one big comparable integer value. Two timestamp values are subtracted and if the result is negative, it means the second is bigger value. For example:
SET /A C=%A% - %B%
IF "%C%" == "-" ECHO B is bigger
Here it goes:
REM %~1 is first file name that needs to be compared to
REM %~2 is second file name that needs to be compared to
REM %~3 is return variable name; if "%~1 > %~2" is true in terms of timestamp, it returns 1; otherwise 0.
IF "%~3" == "" GOTO :EOF

FOR /F "TOKENS=1,2,3" %%A IN ('DIR /A-D %~1 ^| FIND "/"' ) DO SET DATE1=%%A %%B %%C
FOR /F "TOKENS=1,2,3" %%A IN ('DIR /A-D %~2 ^| FIND "/"' ) DO SET DATE2=%%A %%B %%C

SET /A TIMESTAMP1=%DATE1:~8,1%*60*24*31*12*10+%DATE1:~9,1%*60*24*31*12+%DATE1:~0,1%*60*24*31*10+%DATE1:~1,1%*60*24*31+%DATE1:~3,1%*60*24*10+%DATE1:~4,1%*60*24+%DATE1:~11,1%*60*10+%DATE1:~12,1%*60+%DATE1:~14,1%*10+%DATE1:~15,1%
SET /A TIMESTAMP2=%DATE2:~8,1%*60*24*31*12*10+%DATE2:~9,1%*60*24*31*12+%DATE2:~0,1%*60*24*31*10+%DATE2:~1,1%*60*24*31+%DATE2:~3,1%*60*24*10+%DATE2:~4,1%*60*24+%DATE2:~11,1%*60*10+%DATE2:~12,1%*60+%DATE2:~14,1%*10+%DATE2:~15,1%
IF "%DATE1:~17,1%" == "P" SET /A TIMESTAMP1=%TIMESTAMP1% +12*60
IF "%DATE2:~17,1%" == "P" SET /A TIMESTAMP2=%TIMESTAMP2% +12*60


SET "%~3=1"
IF "%TIMEDIFF:~0,1%" == "-" SET "%~3=0"
IF "%TIMEDIFF%" == "0" SET "%~3=0"
And here is how you use it:
CALL :COMPARE_TIMESTAMP_GT a.txt b.txt timediff
IF "%timediff%" ==  "1" ECHO a.txt is newer than b.txt
IF "%timediff%" ==  "0" ECHO b.txt is newer than a.txt or their timestamp is same.
I found this very useful so far. If anyone find bugs, you are welcome to suggest in comment section below.

Nov 16, 2013

Antlr for C# target generates file instead of XXXLexer.cs

I encountered an issue that Antrl4 generates java source code of Lexer instead of c-sharp source code. It turned out that it is a bug in the Antlr4 tool.

Instead of using "options{ language=CSharp_v4_5 }", the target language name should be passed into the tool as an input argument:
java org.antlr.v4.Tool %* -Dlanguage=CSharp_v4_5
With the argument, it generated .cs version of Lexer.