首页 文章

计算下个月的最后一天

提问于
浏览
2

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

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

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

DateTime firstDayNextMonth = DateTime.Today.AddDays(-DateTime.Now.Day+1).AddMonths(1);

5 回答

  • 10
    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

  • 0
    //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);
    
  • 0
    DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month);
    
  • 1
    var lastDayInNextMonth = DateTime.DaysInMonth(DateTime.Now.AddMonths(1).Year, DateTime.Now.AddMonths(1).Month );
    

    @本: DateTime.Now.AddMonths(1)1 月添加到当前日期不减去 11 个月 .

    enter image description here

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

  • 0

    试试这个:

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

相关问题