Tuesday, 3 July 2012

ASP: how to use dateadd


ASP is a powerful tool. Here, as usual, we are talking about a VBScript function that let us manipulate dates: DateAdd.
Whenever we need to perform operations on a date, we can benefit from the use of the this function. In the following post we are going to see how to use it.
DateAdd is used to add a specific time interval to a date. The output is a new date, which value is the sum of the original date, plus the time interval.
It is mainly used to calculate a future date, starting from a given date, however we can use it even to calculate a date in the past. The function is obviously taking into account the calendar, considering the number of days in a month accordingly.
The function syntax is:
DateAdd(interval, interval_value, date)
The three parameters are used to determine how many years, months, days, hour and so on we want the new date be, starting from the given date.
The interval parameter can be:
  1. yyyy - Year
  2. q - Quarter
  3. m - Month
  4. y - Day of year
  5. d - Day
  6. w - Weekday
  7. ww - Week of year
  8. h - Hour
  9. n - Minute
  10. s - Second
We just need to use the needed interval, put in quote.
The interval_value is the number of interval we want to add. Great is the possibility to use positive or negative values. The positive value will be added to the original date, the negative will be added but - if you know maths a little - it will make our date go back in time.
Finally the date parameter: it represent the date from which to start the calculation, the date to which the interval will be added.

Let's see an example.
Starting from a simple one, we can add one year to a given date:
The result will be  03/07/13
Remember that a date includes the time. That means we can can add an hour to a given date:
<%response.write(DateAdd("h",1,"03-Jul-12 07:00:00"))%>
The result will be 03/07/12 08:00:00
Isn't it simple?
If we use negative numbers, we are going back in time:
will give 03/07/11 (one year back!)

And that is all. Next time we are going to see the DateDiff function, which is quite handy...

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.