VBScript – Date Arithmetic – Date & Time

In most cases, you don't need any special functions to perform date arithmetic. All you need to know is that the integer part in a Date variable holds the date information, and the fractional part holds the time information:

' 2 days and 12 hours from now
Print Now + 2 + #12:00# ' Displays "8/17/2008 8:35:48 A.M."

For more sophisticated date math, you can use the DateAdd function, for which the syntax is the following:

NewDate = DateAdd(interval, number, date)

The interval is a string that indicates a date or time unit (see table below), number is the number of units you are adding, and date is the starting date.

You can use this function to add and subtract date and time values:

' The date three months from now
Print DateAdd("m", 3, Now) ' Displays "11/14/2008 8:35:48 P.M."
' One year ago (automatically accounts for leap years)
Print DateAdd("yyyy", -1, Now) ' Displays "8/14/2007 8:35:48 P.M."
' The number of months since Jan 30, 2008
Print DateDiff("m", #1/30/2008#, Now) ' Displays "7"
' The number of days since Jan 30, 2008 _ you can use "d" or "y".
Print DateDiff("y", #1/30/2008#, Now) ' Displays "196"
' The number of entire weeks since Jan 30, 2008
Print DateDiff("w", #1/30/2008#, Now) ' Displays "28"
' The number of weekends before 21st century - value <0 means future dates.
' Note: use "ww" to return the number of Sundays in the date interval.
Print DateDiff("ww", #1/1/2000#, Now) ' Displays "-72"

When you have two dates and you want to evaluate the difference between them—that is, the time elapsed between one date and the next—you should use the DateDiff function, for which the syntax is:

Result = DateDiff(interval, startdate, enddate [, FirstDayOfWeek[, FirstWeekOfYear]])

Where interval has the meaning shown previously, FirstDayOfWeek is an optional argument that you can use to specify which weekday should be considered as the first day of the week (you can use the constants vbSunday, vbMonday, and so on), and FirstWeekOfYear is another optional argument that lets you specify which week should be considered as the first week of the year.

Possible values for the FirstWeekOfYear argument in the DateDiff function.