How do you find the last day of the month? [duplicate]
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?
How about using DaysInMonth
:
DateTime createDate = new DateTime (year, month,
DateTime.DaysInMonth(year, month));
(Note to self - must make this easy in Noda Time...)
You can use the method DateTime.DaysInMonth(year,month)
to get the number of days in any given month.
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.
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; }
精彩评论