DateAdd - VBScript


Overview

The DateAdd function in VB Script allows you to perform basic date and time arithmetic, such as adding or subtracting a specified number of days, months, years, hours, minutes, or seconds from a given date or time. This function is particularly useful for manipulating dates and times in a script or program, making it easier to perform calculations or create dynamic date-related content.

Syntax

DateAdd(interval, number, date)
  • interval: The interval of time to add or subtract. Valid intervals include “y” (years), “q” (quarters), “m” (months), “d” (days), “w” (weeks), “h” (hours), “n” (minutes), and “s” (seconds).
  • number: The number of intervals to add or subtract. Can be a positive or negative value.
  • date: The date or time to which the interval is applied. Can be a Date object or a string representation of a date.

Options/Flags

  • None: No options or flags are available for DateAdd.

Examples

  • Add 5 days to the current date:
Dim currentDate
Dim newDate

currentDate = Date

newDate = DateAdd("d", 5, currentDate)

WScript.Echo "New date: " & newDate
  • Subtract 2 months from a specified date:
Dim specifiedDate
Dim newDate

specifiedDate = #2023-04-01#

newDate = DateAdd("m", -2, specifiedDate)

WScript.Echo "New date: " & newDate
  • Add 1 hour and 30 minutes to a specified time:
Dim specifiedTime
Dim newTime

specifiedTime = #12:30:00 PM#

newTime = DateAdd("h", 1, specifiedTime)
newTime = DateAdd("n", 30, newTime)

WScript.Echo "New time: " & newTime

Common Issues

  • Invalid interval: If you specify an invalid interval, such as “f” for “fortnights,” DateAdd will generate an error.
  • Invalid date: If you provide a date in an incorrect format, such as “2023/04/01” instead of “#2023-04-01#,” DateAdd may return an incorrect result.
  • Invalid number: If you enter a non-numeric value for the number parameter, DateAdd will generate an error.

Integration

DateAdd can be combined with other VB Script commands to perform more complex date and time manipulations. For example, you could use the FormatDate function to convert a date to a specific format after adding or subtracting an interval using DateAdd.

  • DateDiff: Calculates the difference between two dates or times.
  • DatePart: Extracts a specific part of a date, such as the year or month.
  • FormatDate: Converts a date or time to a specified format.