Daily Newbie - 05/01/2001
“To Start Things
Adding a specified time period to a date value.
VB Help Description: Returns a Variant (Date) containing a date to which a specified time interval has been added.
English: Allows you to add a specified number of seconds, minutes, hours, days, weeks, months, quarters, or years to a date.
Syntax: Val=DateAdd(Interval, Count, BaseDate)
Usage:dtmNewDate = DateAdd("M", 8, "01/12/2000")
If you have not read the Daily Newbie on how VB stores date format, you may want to review it now by clicking here.
Interval - The unit that you want to add to the Base Date. This can be:
Count - The number of days, weeks, etc. that you wish to add to the date.
BaseDate - The date that the interval is to be added to.
s - Seconds
n - Minutes
h - Hours
d - Days
w - Weeks
m - Months
q - Quarter
yyyy - Year
To add two days to today's date:
MsgBox DateAdd("d", 2, Date)
Today's code snippet prints a annual schedule of maintenance dates for a piece of equipment that must be maintained every 45 days.
Copy & Paste Code:
Dim dtmStartDate As Date'Holds original date
Dim dtmMaintDate As Date'Holds incremented date
dtmStartDate = InputBox("Enter the date of the first maintenance:")
dtmMaintDate = dtmStartDate 'Start increment date at entered date
Debug.Print "Maintenance Schedule for Widget"
dtmMaintDate = DateAdd("d", 45, dtmMaintDate)
' Print to the debug window (press "Ctrl" Key + "G" Key
' to view the debug window
' keep going until the current maintenance date is
' greater than the start date plus one year
Loop Until dtmMaintDate > DateAdd("yyyy", 1, dtmStartDate)
The DateAdd function is extremely useful when you are writing time sensitive applications. You can accomplish with one function call what would take many, many lines of code without it.
Some general notes on DateAdd:
Despite its name, you can subtract dates with DateAdd as well. This is accomplished by simply adding a negative number in the Count parameter.
MsgBox DateAdd("d", -2, Date)
DateAdd is aware of all of the calendar weirdness such as leap years. Using it to add an interval of one day to Feb. 28, 2001 will yield Feb. 29, while it will yield March 1 for 2002.