VBScript has a useful function called DateDiff that will return a time interval between two dates. You can specify whether want the interval in months, days, minutes among other things.
d1=Now
d2=CDate(“Jan 1, 2008 12:00AM”)
WScript.Echo “Countdown to the New Year (” & d2 & “)”
WScript.Echo ” Months: ” & DateDiff(“m”,d1,d2)
WScript.Echo ” Weeks: ” & DateDiff(“w”,d1,d2)
WScript.Echo ” Days: ” & DateDiff(“d”,d1,d2)
WScript.Echo ” Hours: ” & DateDiff(“h”,d1,d2)
WScript.Echo ” Minutes: ” & DateDiff(“n”,d1,d2)
My problem is that I can never remember what abbreviation to use for the interval. In PrimalScript 2007 this isn’t necessarily a big deal because I can use the help file from WSH and VBScript Core: TFM. But maybe I can improve on this. How about a function that I can use in my script to return a date/time interval that uses “real” English?
Function GetDateDiff(dtOne,dtTwo,sInterval)
’ Valid interval values are:
’ Months,Days,Minutes,Hours,Seconds and they
’ are not case sensitive
Select Case LCase(sInterval)
Case “months”
result = DateDiff(“M”,dtOne,dtNow)
Case “days”
result = DateDiff(“d”,dtOne,dtNow)
Case “minutes”
result = DateDiff(“n”,dtOne,dtNow)
Case “hours”
result = DateDiff(“h”,dtOne,dtNow)
Case “seconds”
result = DateDiff(“s”,dtOne,dtNow)
Case Else result=”Unknown interval”
End Select
GetDateDiff=result
End Function
This function allows me to specify a date interval using a meaningful word like months or days. Now I don’t have to remember that “n” means minutes. I mean, who’s going to make that association? Using a function like this allows me to write more meaningful VBScript code:
dtThen=#11/28/2007 11:41 AM#
dtNow=Now
WScript.Echo dtThen & ” was: ”
WScript.Echo GetDateDiff(dtThen,dtNow,”months”) &_
” months ago from ” & dtNow
WScript.Echo GetDateDiff(dtThen,dtNow,”days”) &_
” days ago from ” & dtNow
WScript.Echo GetDateDiff(dtThen,dtNow,”hours”) &_
” hours ago from ” & dtNow
WScript.Echo GetDateDiff(dtThen,dtNow,”minutes”) &_
” minutes ago from ” & dtNow
WScript.Echo GetDateDiff(dtThen,dtNow,”seconds”) &_
” seconds ago from ” & dtNow
Now I don’t have to rely on middle-aged memory and the code is a little more meaningful. I haven’t wrapped all the functionality from DateDiff into my function so if there is something you need, you’ll need to modify it. But this should meet 95% or more of my needs.
I’ve attached the function and sample code as a text file so you don’t have to try and copy/paste from the blog entry.