0

Following are two ways of adding days and months to a given date. Both seem to be logically correct but returns different values.

Column number 1: Add months and then days, Column number 2: Add days and then months

DECLARE @d DATE = '20140128'

SELECT  DATEADD(DAY, 3, DATEADD(MONTH, 1, @d)) Add_Months_Days,  
        DATEADD(MONTH, 1, DATEADD(DAY, 3, @d)) Add_Days_Months

Results and fiddle

Add_Months_Days        Add_Days_Months
----------------       ----------------
2014-03-03             2014-02-28

I understand why it is happening and both are logical too. But in a situation where we need to add months and days to a given date at the same time, is there a standard way to do this?

Kaf
  • 33,101
  • 7
  • 58
  • 78
  • It is correct actually but you are interpreting it wrongly. – Rahul Aug 11 '14 at 09:25
  • *you* need to work out what is actually logical for *your* situation and then decide whether either of the above is actually what you want. As you say, both results are logical. The problems all stem from variable length months, and until you eliminate those, there isn't one, standard definition for what it means to add 1 month and 3 days onto a particular given date. – Damien_The_Unbeliever Aug 11 '14 at 10:02

3 Answers3

0

I believe they are both correct, but they do different things.

MSDN states:

If datepart is month and the date month has more days than the return month and the date day does not exist in the return month, the last day of the return month is returned.

In the first example you first add 1 month to 20140128 making it 20140228 (a valid date) and then add 3 days, ending up with 20140303.

In the second example however you add 3 days, getting 20140131 and then add 1 month, but since February 2014 only has 28 days you'll get 20140228 as the result as the dateadd operation returns the last day of the month as stated above.

I don't believe there is a standard way of doing this, I would think it comes down to the specific business requirements, however I personally think doing month-day and getting the latter end date might be "more correct" as it seem to follow from the intent (the day-month method seem to lose a few days).

jpw
  • 44,361
  • 6
  • 66
  • 86
0

They are both logical but return different results as implicit in your question is the truncation of the add-month result to month-end, should it take you over a month-boundary. You have this in the second query, but not the first.

davek
  • 22,499
  • 9
  • 75
  • 95
0

Adding MONTH (1) to a date ("20140128"), will not add total days of the month (Jan - 31, Feb - 28 or 29, etc.). It will add the given MONTH value (1) to the input date and result will be "20140228".

Please refer this Question and Answer

Community
  • 1
  • 1
Jesuraja
  • 3,774
  • 4
  • 24
  • 48