Sunday, April 28, 2013

Adding and Subtracting Days datatage

Adding and Subtracting Days
Converting to Julian date is quite a common way of performing date arithmetic. Once you have a Julian day, you can simply add or subtract any number of days from the original value.
JDATE = JulianDayFromDate(DT_VAR)
TOMORROW = JDATE + 1
YESTERDAY = JDATE - 1
LAST_WEEK = JDATE - 7
Once you have performed your arithmetic, you simply change back to a date.
NEW_DT = DateFromJulianDay(LAST_WEEK)
Another way is to use the DateFromDaysSince function.
TOMORROW = DateFromDaysSince(1,DT_VAR)
YESTERDAY = DateFromDaysSince(-1,DT_VAR)
The great thing about this function is it will accept a string so long as the string is in the format ("%yyyy-%mm-%dd").
Both options have the same drawback - no options to add months or years. Trying to roll your own functions to add months and years (although fairly simple) is a pain at the best of times and it's just another component that has to be deployed. It would be nice to have a built-in function that does the job - and there is. The best and most flexible option is to use the DateOffsetByComponents function. This function provides almost everything you will need for date aritmetic. The function takes four parameters - date, year_offset, month_offset, day_offset. In other words, this function can perform calculations similar to the following examples.
Use DateOffsetByComponents(%basedate%,%yearoffset%,%monthoffset%,%dayoffset%) to:
  • Calculate the date 5 days before or after date
  • Calculate the date 3 months before or after date
  • Calculate the date 2 years before or after date
  • Calculate the date 2 years, 3 months and 5 days before or after the date
Furthermore, this function also accepts strings in the format "%yyyy-%mm-%dd".
Date Year Offset Month Offset Day Offset Result
2004-02-29 0 0 5 2004-03-05
2004-02-29 0 3 0 2004-05-29
2004-02-29 2 0 0 2006-03-01
2004-02-29 2 3 5 2006-06-03

0 comments:

Post a Comment

Please Post your Comments..!