How do you find the last day of the month?

C#Datetime

C# Problem Overview


> Possible Duplicate:
> How to get the last day of a month?

So far, I have this:

DateTime createDate = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);

Is there a better way?

C# Solutions


Solution 1 - C#

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 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

if you're interested in a custom code version:

var anyDt = DateTime.Now;
var lastDayOfMonth = anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date;

or:

var anyDt = DateTime.Now;
var lastDayOfMonth = anyDt.AddDays(1-anyDt.Day).AddMonths(1).AddDays(-1).Date; 

or as a method:

DateTime LastDayInMonth(DateTime anyDt)
   { return anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date; }

or as an extension method:

DateTime LastDayInMonth(DateTime this anyDt)
   { return anyDt.AddMonths(1).AddDays(anyDt.AddMonths(1).Day).Date; }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIrwinView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Øyvind BråthenView Answer on Stackoverflow
Solution 3 - C#DonaldView Answer on Stackoverflow
Solution 4 - C#Charles BretanaView Answer on Stackoverflow