繁体   English   中英

计算下个月的最后一天

[英]Calculate Last Day of the Next Month

我试图在C#中使用DateTime函数来计算下个月的最后一天。

例如,今天是2015年12月17日。我希望DateTime函数返回2016年1月31日(下个月的最后一天)。

我使用以下来计算下个月的第一天(这是有效的):

DateTime firstDayNextMonth = DateTime.Today.AddDays(-DateTime.Now.Day+1).AddMonths(1);
DateTime reference = DateTime.Now;
DateTime firstDayThisMonth = new DateTime(reference.Year, reference.Month, 1);
DateTime firstDayPlusTwoMonths = firstDayThisMonth.AddMonths(2);
DateTime lastDayNextMonth = firstDayPlusTwoMonths.AddDays(-1);
DateTime endOfLastDayNextMonth = firstDayPlusTwoMonths.AddTicks(-1);

演示: http//rextester.com/AKDI52378

//system date or any date u want this case it is a calendar picker - 22/03/2016
DateTime today = dtpFrom.Value;

//Add a month to your date example , it now becomes - 22/04/2016
DateTime endOfMonth = new DateTime(today.Year, today.Month,today.Day).AddMonths(1);

//Get the last date off the above which is - 30
int getlastday = DateTime.DaysInMonth(endOfMonth.Year, endOfMonth.Month);

//Now set the date to the value  which will be the last day off the next month - 30/04/2016
DateTime newDate = new DateTime(endOfMonth.Year, endOfMonth.Month, getlastday);

尝试这个:

int Day= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month+1>12 ? 01 : DateTime.Now.Month+1 );
 var lastDayInNextMonth = DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month );  

@ Ben: DateTime.Now.AddMonths(1)将在当前日期增加1个月而不减去11个月。

在此输入图像描述

DateTime.Now.AddMonths(1).Year将给2016而不是2015参考附图

DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM