As I said in my last post, today we are going to explore a VBScript function called DateDiff. There's not much mystery behind it, in fact, as the name says, DateDiff calculates the difference between two dates. The resulting value can be in different format and, generally speaking, the function can be used in many situations.
let's see how it works.
DateDiffThe function syntax is a little bit more complicated than DateAdd.
DateDiff(interval,date1,date2[,firstdayofweek[,firstweekofyear]])The first three parameters are quite easy to understand.
As in DateAdd, the interval is a required parameter and it is used to calculate difference between date1, and date2. It can be:
- yyyy - Year
- q - Quarter
- m - Month
- y - Day of year
- d - Day
- w - Weekday
- ww - Week of year
- h - Hour
- n - Minute
- s - Second
date1 and date2 are two date expressions; the first represents from which date we want to start the calculation, and date2 is the end date.
After those three required parameters, we have two optional parameters: firstdayoftheweel and firstweekofyear.
firstdayoftheweek can be:
- 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting
- 1 = vbSunday - Sunday (default)
- 2 = vbMonday - Monday
- 3 = vbTuesday - Tuesday
- 4 = vbWednesday - Wednesday
- 5 = vbThursday - Thursday
- 6 = vbFriday - Friday
- 7 = vbSaturday - Saturday
firstweekofyear can be:
- 0 = vbUseSystem - Use National Language Support (NLS) API setting
- 1 = vbFirstJan1 - Start with the week in which January 1 occurs (default)
- 2 = vbFirstFourDays - Start with the week that has at least four days in the new year
- 3 = vbFirstFullWeek - Start with the first full week of the new year
ExamplesWe could make many examples for DateDiff, but if you start using it, the result will be clear enough. I'm saying that the following examples cannot replace experience. Just try to use the function, and you will immediately understand its logic.
Anyway... let's say we have two dates like: "5-Jul-2012" and "5-Jul-2011".
What's the difference in years between the two dates (I know you know!):
startDate = "5-Jul-2012 07:00:00"
endDate = "5-Jul-2012 07:00:00"
response.write (datediff("yyyy", startDate, endDate))
1, as you predicted!
response.write (datediff("m", startDate, endDate))
That was easy.
Let's say you want to caluculate how many weeks there are between the two dates. In that case we can set the first day of the week:
and that's it.
response.write (datediff("w", startDate, endDate, vbMonday))
Oh... the result? Calculate it yourself...
That's all for today... Please leave a comment in the section below, if you wish...