JSI Tip 9229. How can I calculate the difference between two date/times?.
Jerold Schulman
April 4, 2005
1 Min Read
In tip 0721, I calculated the difference between two dates. In tip 0863, I performed Time Math.
I have scripted DateTimeDiff.bat to return the difference between two date/times.
The syntax for using DateTimeDiff.bat is:
[call] DateTimeDiff Unit Date1 Time1 Date2 Time2 Diff
Where:
Unit can be D to return the difference in whole days, H to return the difference in whole hours, N to return the difference in whole minutes, S to return the difference in seconds.Date1 First date in your date format, like MM/DD/YYYY. Quotes are NOT allowed.Time1 The time on Date1, in your time format, like HH:MM:SS. Quotes are NOT allowed.Date2 Second date in your date format, like MM/DD/YYYY. Quotes are NOT allowed.Time2 The time on Date2, in your time format, like HH:MM:SS. Quotes are NOT allowed.Diff is a call directed numeric environment variable that will contain the difference, in Unit units, between the two date/times. If date/time 1 is greater than date/time 2, Diff we be negative. If the parameters are incorrect, Diff will be -99999999.
Example:
To calculate the number of hours until Christmas:
call DateTimeDiff H %DATE% %TIME:~0,8% 12/25/%DATE:~6,4% 00:00:00 Hours
@echo The number of hours until Christmas is %Hours%
DateTimeDiff.bat contains:
@echo offif {6}=={} @echo Syntax: DateTimeDiff Unit Date1 Time1 Date2 Time2 Diff&goto :EOFif exist "%TEMP%DateTimeDiff.vbs" goto vbs@echo dim unt, dt1, dt2, dif, objArguments>"%TEMP%DateTimeDiff.vbs"@echo set objArguments = Wscript.Arguments>>"%TEMP%DateTimeDiff.vbs"@echo unt=objArguments(0)>>"%TEMP%DateTimeDiff.vbs"@echo dt1=objArguments(1)>>"%TEMP%DateTimeDiff.vbs"@echo dt2=objArguments(2)>>"%TEMP%DateTimeDiff.vbs"@echo dif=datediff(unt,dt1,dt2)>>"%TEMP%DateTimeDiff.vbs"@echo WScript.Echo dif>>"%TEMP%DateTimeDiff.vbs":vbsset /a %6=-99999999for /f "Tokens=*" %%d in ('cscript //nologo "%TEMP%DateTimeDiff.vbs" %1 "%2 %3" "%4 %5"') do set /a %6=%%d
About the Author
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.
You May Also Like