如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
如何在c#中找到一个月的最后一天?
例如,如果我有日期03/08/1980,我如何得到第8个月的最后一天(在本例中是31)?
当前回答
这将显示下个月的最后日期。可以从AddMonths(x)中添加或减去想要返回的月份。
DateTime.Now.AddMonths(2).AddDays(-DateTime.Now.Day)
其他回答
从DateTimePicker:
第一次约会:
DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);
最后的日期:
DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));
如果你想要日期,给定一个月和一年,这似乎是正确的:
public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}
这个月的最后一天你会得到这样的结果,返回31:
DateTime.DaysInMonth(1980, 08);
您可以按以下方式扩展DateTime;
public static class DateTimeMethods
{
public static DateTime StartOfMonth(this DateTime date)
{
return new DateTime(date.Year, date.Month, 1, 0, 0, 0);
}
public static DateTime EndOfMonth(this DateTime date)
{
return date.StartOfMonth().AddMonths(1).AddSeconds(-1);
}
}
像这样使用它;
DateTime today = DateTime.Now;
DateTime startOfMonth = today.StartOfMonth();
DateTime endOfMonth = today.EndOfMonth();
这个公式反映了@RHSeeger的想法,作为一个简单的解决方案,以获得(在这个例子中)第3个月的最后一天(单元格A1 + 4中的日期月份,该月的第一天减去1天):
=DATE(YEAR(A1);MONTH(A1)+4;1)-1
非常精确,包括闰年的二月。