Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn DateTime to last day of the month?

Tags:

c#

.net

datetime

If I have a DateTime which is, for example, 2012-05-24, what is the quickest way to convert it to a date which is the last day of that month (2012-05-31).

like image 748
CJ7 Avatar asked Aug 21 '13 05:08

CJ7


2 Answers

Well you can use:

DateTime date = ...;
var endOfMonth = new DateTime(date.Year, date.Month, 
                              DateTime.DaysInMonth(date.Year, date.Month));

Note that that will create a DateTime with a Kind of Unspecified. You should consider what Kind you really want. (Or use my Noda Time library, where you'd use a LocalDate instead.)

like image 50
Jon Skeet Avatar answered Oct 29 '22 07:10

Jon Skeet


Here's some extension methods I use:

public static class DateTimeExtensionMethods
{
    public static DateTime StartOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, 1);
    }
    public static DateTime EndOfMonth(this DateTime date)
    {
        return date.StartOfMonth().AddMonths(1).AddSeconds(-1);
    }
}

Note that in my case I'm using them for SQL queries, so I want it to be up to the last second of the last day of the month.

Based on comments, yes, if you want just want the date and not time, you could use:

    public static DateTime EndOfMonth(this DateTime date)
    {
        return date.StartOfMonth().AddMonths(1).AddDays(-1);
    }

Or just use the Date property of the result to just get the date portion, then it satisfies both cases depending how you use it.

like image 45
Timothy Walters Avatar answered Oct 29 '22 07:10

Timothy Walters