How to find the first day of next month,if the current month is december

前端 未结 10 1935
独厮守ぢ
独厮守ぢ 2021-01-01 11:03

I\'m using the following query to get the next month.

int theMonth = ((System.DateTime)periodStartDate).Month+1;

But if the periodstartDate

相关标签:
10条回答
  • 2021-01-01 12:02

    after you compute theMonth, check whether it equals to 13 (the month after December) and replace the value with 1:

    theMonth = theMonth==13 ? 1 : theMonth;
    
    0 讨论(0)
  • 2021-01-01 12:03
        DateTime nextMonthStartDate= DateTime.Parse(startdate.Year + "-" + startdate.AddMonths(1).Month + "-01");
    

    This will work in leap year or non leap year. In the above converting strings to date time with static date 1 coz always taking start of the month. Hope it is useful

    0 讨论(0)
  • 2021-01-01 12:04

    I like V4V's answer, but I write it this way:

    DateTime dt = new DateTime(2011,12,2);
    DateTime firstDayNextMonth = dt.AddMonths(1).AddDays(-dt.Day+1);
    

    For example, I might be computing a future time and this code does that without stripping out the time part.

    Per hvd's most astute comment, this code should be:

    DateTime dt = new DateTime(2011,12,2);
    DateTime firstDayNextMonth = dt.AddDays(-dt.Day+1).AddMonths(1);
    
    0 讨论(0)
  • 2021-01-01 12:05
    DateTime date = DateTime.Now;
    Console.WriteLine(date);
    // Sunday 28.06.2015 г. 10:22:41 ч.
    
    int monthsBack = -1;
    int whichDay = 1;
    // It means -> what day the first day of the previous month is.
    DayOfWeek FirstDayOfWeek = date.AddMonths(monthsBack).AddDays(whichDay).DayOfWeek;
    Console.WriteLine(FirstDayOfWeek);
    // Friday
    
    int delta = DayOfWeek.Monday - date.AddMonths(monthsBack).AddDays(whichDay).DayOfWeek;
    Console.WriteLine(delta);
    // -4
    //-4 ->Monday , -3 ->Tuesday, -2 ->Wednesday , -1 ->Thursday, 0 ->Friday
    
    0 讨论(0)
提交回复
热议问题