How do you find the last day of the month? [duplicate]

Solution 1:

How about using DaysInMonth:

DateTime createDate = new DateTime (year, month,
                                    DateTime.DaysInMonth(year, month));

(Note to self - must make this easy in Noda Time...)

Solution 2:

You can use the method DateTime.DaysInMonth(year,month) to get the number of days in any given month.

Solution 3:

Here's an elegant approach I found in a useful DateTime extension library on CodePlex:

http://datetimeextensions.codeplex.com/

Here's some sample code:

    public static DateTime First(this DateTime current)
    {
        DateTime first = current.AddDays(1 - current.Day);
        return first;
    }

    public static DateTime First(this DateTime current, DayOfWeek dayOfWeek)
    {
        DateTime first = current.First();

        if (first.DayOfWeek != dayOfWeek)
        {
            first = first.Next(dayOfWeek);
        }

        return first;
    }

    public static DateTime Last(this DateTime current)
    {
        int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);

        DateTime last = current.First().AddDays(daysInMonth - 1);
        return last;
    }

It has a few other useful extensions as well that may be helpful to you.