How Can I Determine the Elapsed Time Between Two Dates?

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I tell how many days there are between two dates? For example, if I have a log file that says an application started on January 1, 2005 and that the application ended today, is there a way to determine how many days the application ran?

— AL

SpacerHey, Scripting Guy! AnswerScript Center

Hey, AL. You know, in the second Hey, Scripting Guy! column ever written (“How Can I Get Yesterday’s Date?”), we talked about simple date arithmetic. For some reason, though, we didn’t talk about this kind of date arithmetic, the ability to determine elapsed time between two dates. So let’s rectify that right now.

As it turns out, doing date arithmetic such as this is remarkably easy with VBScript; that’s because VBScript includes a DateDiff function designed to carry out calculations such as this. Want to know the number of days between today and January 1, 2005? Then just use a script like this one:

dtmEndingDate = Date
intDays = DateDiff(“d”, #1/1/2005#, dtmEndingDate)
Wscript.Echo intDays

Yep, that’s it: just three lines of code. We begin by assigning today’s date (Date) to a variable named dtmEndingDate; that’s what this line of code does:

dtmEndingDate = Date

We then call the DateDiff function and store the results in a variable named intDays; that’s what this line of code does:

intDays = DateDiff(“d”, #1/1/2005#, dtmEndingDate)

Note that DateDiff requires three parameters. First, we need to indicate the time interval we’re using. For this script we’re using days, so we pass the parameter “d”. We could also use time intervals such as hours (“h”), weeks (“w”), or months (“m”). For a complete list, see “Working with Dates and Times” in the Microsoft Windows 2000 Scripting Guide.

Second, we need to indicate the starting date (in this case, 1/1/2005); note that we surround the date using pound signs (#) to ensure that VBScript interprets the value as a date.

Finally, we indicate the ending date. VBScript will calculate the number of days between the two dates and stash that number in the variable intDays. At that point all we have to do is to echo back the elapsed time.

As we noted, you can use different time intervals; you’re not limited to just days. For example, suppose you know that your application started at 8:00 AM on January 1, 2005 and ended at 9:30 PM on January 5, 2005. Want to know how many hours the application was running? Here’s a script that does just that:

intHours = DateDiff _
(“h”, #1/1/2005 8:00 AM#, #1/5/2005 9:30 PM#)
Wscript.Echo intHours

Note that the value returned will be rounded to the nearest hour. To get even more specific, you could calculate the elapsed time in minutes and then divide by 60 in order to determine hours and fraction of an hour. But we’ll leave that up to you.