Daily Newbie - 04/25/2001
“To Start Things
Today's Newbie code is the result of a request from a reader of yesterdays (thanks for the suggestion BigCalm).
Today I am going to discuss the DateDiff() function. Many newbies (and some more experienced coders) spend many hours writing code to do the exact same things that they could do with a single call to DateDiff(). I hope to show you what this function is, how to use it, and how it can make your coding MUCH easier.
"Date Difference "
Determining the difference between two dates or times.
VB Help Description: Returns a Variant (Long) specifying the number of time intervals between two specified dates.
English: Makes adding and subtracting dates easier by allowing you to pass in a start and end date and get difference back. This difference can be in any valid date/time increment (day, week, month, quarter, year, hour, minute, second).
Syntax: X = DateDiff(Interval, StartDateTime, EndDateTime)
Usage:intDayCount = DateDiff("d","01/01/1995", "01/01/2001")
Parameters:Interval - The type of results you want returned. These are:
y =Day of year
StartDateTime - Any valid date, time, or datetime combination. Examples: "01/01/2000" , "01/01/2000 12:25 AM" , "16:30"
EndDateTime - Same criteria as StartDateTime. This is the data the start date will be subtracted from.
Copy & Paste Code:
Dim StartDate As Date
Dim EndDate As Date
Dim Interval As String
StartDate = InputBox ("Start Date:")
EndDate = InputBox ("End Date:")
Interval = InputBox ("Return In:s=seconds, m=Minutes h=Hours, d=Days, ww=Weeks, w=WeekDays, yyyy=years"
MsgBox DateDiff(Interval, StartDate, EndDate)
The DateDiff() function is one of the most useful ones VB has to offer. It literally replaces thousands of lines of code, takes in account leap years, knows how many days and weeks are in a month, and many other things that typically trip up home-brewed date code. Let's face it...those Microsoft guys can write some decent code. They went to a lot of trouble to create these functions in lower level languages so we could just call it and get a result back. Besides being much less likely to error out that your own code, it is also exponentially faster since it exists as true bytecode.
A couple of things to watch out for in the DateDiff() Function are:
Times can mess you up. When you call DateDiff without specifying a time (i.e. "01/10/200" instead of "01/01/2000 9:25:00"), DateDiff assumes a time of midnight (00:00:01). This can have the effect of "skipping" a day if you aren't careful. Check your results a few times and adjust your dates or times to make it right. Once you have it, it will always work the same.
Switching dates will return negative values. Not a tragedy, but something you should be aware of.
Well I hope today's newsletter has helped save some newbie coders out there from pulling out clumps of hair over date manipulation. If you need more details on using DateDiff() please let me know.