DateDiff - VBScript


Overview

The DateDiff command in VB Script allows you to find the difference between two dates, expressed as a number representing the specified interval. It is particularly useful for comparing dates, calculating time spans, and performing date arithmetic.

Syntax

DateDiff(interval, date1, date2, firstdayofweek, firstweekofyear)

Parameters:

  • interval: The interval to calculate the difference for. Valid options are:
    • “y” or “yyyy”: Years
    • “m” or “mm”: Months
    • “d” or “dd”: Days
    • “h” or “hh”: Hours
    • “n” or “nn”: Minutes
    • “s” or “ss”: Seconds
  • date1: The earlier date to compare.
  • date2: The later date to compare.
  • firstdayofweek (optional): The first day of the week. Default is 1 (Sunday).
  • firstweekofyear (optional): The first week of the year. Default is 1 (first week of January).

Options/Flags

  • firstdayofweek: Specifies which day is considered the first day of the week for week-based intervals ("w").
  • firstweekofyear: Specifies which week is considered the first week of the year for year-based intervals ("y").

Examples

Simple example:

Dim date1 = #2023-03-08#
Dim date2 = #2023-04-10#
Dim diff = DateDiff("d", date1, date2)
MsgBox diff 

Output: 33

More complex example:

Dim date1 = #2023-02-28#
Dim date2 = #2023-03-08#
Dim diff = DateDiff("m", date1, date2, 1, 1)
MsgBox diff 

Output: 1

Common Issues

  • Incorrect date format: Ensure that dates are in the correct format ("#yyyy-mm-dd#") to avoid errors.
  • Invalid interval: The interval must be one of the specified valid options.
  • Negative difference: If date1 is later than date2, the difference will be negative.

Integration

  • Combine with the DateAdd command to perform date arithmetic.
  • Use with loops to iterate over date ranges and perform calculations.
  • Integrate with other date-related commands or functions to manipulate and compare dates.
  • DateAdd
  • DateFormat
  • DateParse
  • DateSerial
  • Now