Last day of the month in .NET

后端 未结 5 1701
闹比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:20

    Here is how you can get the number of days in the month using Noda Time:

    int days = CalendarSystem.Iso.GetDaysInMonth(year, month);
    

    Pretty simple, eh? Well that assumes you know the year and month you are asking about. If you want it for the current month, and in the system's time zone, then you have to specify that explicitly, like this:

    DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault();
    LocalDate localDate = SystemClock.Instance.Now.InZone(tz).Date;
    int days = localDate.Calendar.GetDaysInMonth(localDate.Year, localDate.Month);
    

    Noda Time intentionally makes you think about these things, instead of just making the assumptions that DateTime.Now or DateTime.Today do.

提交回复
热议问题