Get the previous month's first and last day dates in c#

后端 未结 10 1519
眼角桃花
眼角桃花 2020-12-02 06:28

I can\'t think of an easy one or two liner that would get the previous months first day and last day.

I am LINQ-ifying a survey web app, and they squeezed a new requ

10条回答
  •  温柔的废话
    2020-12-02 06:50

    DateTime now = DateTime.Now;
    int prevMonth = now.AddMonths(-1).Month;
    int year = now.AddMonths(-1).Year;
    int daysInPrevMonth = DateTime.DaysInMonth(year, prevMonth);
    DateTime firstDayPrevMonth = new DateTime(year, prevMonth, 1);
    DateTime lastDayPrevMonth = new DateTime(year, prevMonth, daysInPrevMonth);
    Console.WriteLine("{0} {1}", firstDayPrevMonth.ToShortDateString(),
      lastDayPrevMonth.ToShortDateString());
    

提交回复
热议问题