【发布时间】:2011-06-07 00:13:57
【问题描述】:
如何在 C# 中找到一个月的最后一天?
【问题讨论】:
-
DateTime.DaysInMonth(1980, 08);请看这篇文章stackoverflow.com/questions/2493032/…
标签: c#
如何在 C# 中找到一个月的最后一天?
【问题讨论】:
标签: c#
DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)
【讨论】:
另一种方法:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year,
today.Month,
DateTime.DaysInMonth(today.Year,
today.Month));
【讨论】:
DateTime.SpecifyKind( new DateTime(/*...*/) , existingDateTime.Kind) 否则您可能会丢失现有日期时间的时区信息。
public static class DateTimeExtensions
{
public static DateTime LastDayOfMonth(this DateTime date)
{
return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
}
}
【讨论】:
试试这个。它会解决你的问题。
var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);
【讨论】:
string 以便您可以parse it into a DateTime 效率低下并且依赖于当前文化的日期格式。其他三年前的答案提供了更清洁的解决方案。
类似:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
也就是说你得到下个月的第一天,然后减去一天。框架代码将处理月份长度、闰年等等。
【讨论】: