可能重复:
如何获得一个月的最后一天?
到目前为止,我有这个:
DateTime createDate = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
Jon*_*eet 224
如何使用DaysInMonth:
DateTime createDate = new DateTime (year, month,
DateTime.DaysInMonth(year, month));
Run Code Online (Sandbox Code Playgroud)
(注意自己 - 必须在Noda Time中轻松实现......)
这是我在CodePlex上有用的DateTime扩展库中找到的一种优雅方法:
http://datetimeextensions.codeplex.com/
这是一些示例代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
它还有一些其他有用的扩展,可能对您有所帮助.
| 归档时间: |
|
| 查看次数: |
62361 次 |
| 最近记录: |