CJ7
CJ7

Reputation: 23275

How to turn DateTime to last day of the month?

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).

Upvotes: 8

Views: 14342

Answers (4)

Microsoft DN
Microsoft DN

Reputation: 10010

Try this

DateTime date = new DateTime(2012, 05, 24);
DateTime endOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));

Output: 5/31/2012 12:00:00 AM

You can then modify this to your required format.

Upvotes: 1

Timothy Walters
Timothy Walters

Reputation: 16874

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.

Upvotes: 9

Jon Skeet
Jon Skeet

Reputation: 1499740

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.)

Upvotes: 21

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Try this

DateTime dt = DateTime.Parse("2012-05-24");            
DateTime lastDate = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));

Upvotes: 3

Related Questions