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
).
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With