.NET中的最后一天

Jon*_*len 31 .net

通常我使用下面的代码,但有更好的方法吗?

lastOfMonth = new DateTime(Now.Year, Now.Month, 1).AddMonths(1).AddDays(-1)
Run Code Online (Sandbox Code Playgroud)

Mik*_*Two 61

我用

DateTime now = DateTime.Today;
var lastDate = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));
Run Code Online (Sandbox Code Playgroud)


Tom*_*cek 13

我可能会使用DaysInMonth它,因为它使代码更易读,更容易理解(虽然,我真的很喜欢你的技巧:-)).这需要类似的大量输入(这是相当多的),所以我可能会定义一个扩展方法:

DateTime LastDayOfMonth(this DateTime) {
  var days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
  return new DateTime(DateTime.Now.Year, DateTime.Now.Month, days);
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以使用DateTime.Now.LastDayOfMonth()看起来好多了:-).


Kel*_*sey 9

DateTime(year, month, DateTime.DaysInMonth(year, month)).
Run Code Online (Sandbox Code Playgroud)


Tim*_*res 5

您可以使用 CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(Now.Year, Now.Month)