Home > database >  Why does DateTime.AddMonths(3).AddMonths(3); give a different result than DateTime.AddMonths(6);?
Why does DateTime.AddMonths(3).AddMonths(3); give a different result than DateTime.AddMonths(6);?

Time:01-31

I have a unit test where the expected result is a DateTime and is set as follows: var expectedResult = DateTime.Today.AddMonths(3).AddMonths(3);

After which I have a function that adds quarters to a date: DateTime.AddMonths(3 * numberOfTimes);

numberOfTimes is in this case 2.

The results differ in date. Today is 31/01/2023, expected result is 30/07/2023 and the function result is 31/07/2023.

I expected the results to be the same because 6 months should have been equal number of days from the starting date. I am curious why this happens. For now I fixed the problem by doing 3 * numberOfTimes in the expectedResult section.

Just out of curiosity why does this happen?

CodePudding user response:

It is documented:

The AddMonths method calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting DateTime object. If the resulting day is not a valid day in the resulting month, the last valid day of the resulting month is used. For example, March 31st 1 month = April 30th, and March 31st - 1 month = February 28 for a non-leap year and February 29 for a leap year.

So you get a different result because if you add 6 months it just needs to be checked if 31/07/2023 is a valid DateTime, which it is. For DateTime.Today.AddMonths(3).AddMonths(3) it will check first if 31/04/2023 is valid, which is not, so 30/04/2023 is returned, then 3 months are added.

CodePudding user response:

The result can be different because of the way that the date and time is calculated for each method. The DateTime.AddMonths method takes into account the number of days in each month and can result in a different day of the month if the original date has a different number of days in the month. For example, adding 3 months to January 31st would result in a different day of the month than adding 6 months to January 31st.

  • Related