Last day of the month in .NET

后端 未结 5 1717
闹比i
闹比i 2020-12-30 20:12

Normally I use the below code, but is there a better way?

lastOfMonth = new DateTime(Now.Year, Now.Month, 1).AddMonths(1).AddDays(-1)
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 20:31

    I would probably use DaysInMonth as it makes the code a bit more readable and easier to understand (although, I really like your trick :-)). This requieres a similar ammount of typing (which is quite a lot), so I would probably define an extension method:

    DateTime LastDayOfMonth(this DateTime) {
      var days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
      return new DateTime(DateTime.Now.Year, DateTime.Now.Month, days);
    }
    

    Now we can use DateTime.Now.LastDayOfMonth() which looks a lot better :-).

提交回复
热议问题