How can I get the last day of the month in C#?

C#

C# Problem Overview


How can I find the last day of the month in C#?

C# Solutions


Solution 1 - C#

Another way of doing it:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, 
                                   today.Month, 
                                   DateTime.DaysInMonth(today.Year, 
                                                        today.Month));

Solution 2 - C#

Something like:

DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);

Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

Solution 3 - C#

public static class DateTimeExtensions
{
    public static DateTime LastDayOfMonth(this DateTime date)
    {
        return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
    }
}

Solution 4 - C#

DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)

Solution 5 - C#

try this. It will solve your problem.

 var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);

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
QuestionGaliView Question on Stackoverflow
Solution 1 - C#YogeshView Answer on Stackoverflow
Solution 2 - C#SethView Answer on Stackoverflow
Solution 3 - C#MartinCView Answer on Stackoverflow
Solution 4 - C#Haris N IView Answer on Stackoverflow
Solution 5 - C#IsankaView Answer on Stackoverflow