Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End of month calculations

Just wondering if any know of an elegant solution for the following.

If I have 30 June 2009 and I add a month I want it to go to 31 July 2009, not the 30 July 2009.

This logic is based on the fact that the 30 June 2009 was the end of the month of June and when I add a month I want to go to the end of the next month.

But if I have 29 June 2009 and I add a month it should go to 29 July 2009.

Note I need to be able to add any number of months and I need to take into account leap years.

Also I know the logic here is questionable but it is a business requirement that works with end of month contracts going to the end of the month for a month in the future.

I have thought of several solution but none that are very elegant. Hence I was thinking someone might have a better way.

Cheers Anthony

like image 996
vdh_ant Avatar asked Jun 11 '09 02:06

vdh_ant


2 Answers

To check if a date is the end of the month, you check if the next day is day one of some month. your algorithm should then be "If the day is not end of month, add 1 month. If it is the end of the month, add one day, add one month, subtract one day."

    bool IsEndOfMonth(DateTime date) {
        return date.AddDays(1).Day == 1;
    }
    DateTime AddMonthSpecial(DateTime date) {
        if (IsEndOfMonth(date))
            return date.AddDays(1).AddMonths(1).AddDays(-1);
        else
            return date.AddMonths(1);
    }
like image 162
Jimmy Avatar answered Sep 22 '22 19:09

Jimmy


DateTime exampleDate = DateTime.Parse("12/31/2009");
bool isLastDayOfMonth = (exampleDate.AddDays(1).Month != exampleDate.Month);

if (isLastDayOfMonth)
    Console.WriteLine(exampleDate.AddDays(1).AddMonths(1).AddDays(-1));
else
    Console.WriteLine(new DateTime(exampleDate.Year, exampleDate.Month, 1).AddMonths(2).AddDays(-1));

EDIT: I read your question again. You will need to put a check to see if its last day of the month.

Sorry, I wish I had read the question clearly of what is needed.
Hope this is good enough to give you an idea of what is needed.

like image 26
shahkalpesh Avatar answered Sep 20 '22 19:09

shahkalpesh