简体   繁体   English

如何获得当月的最后一天和下个月的最后一天

[英]How to get last day of current month and last day of next month

I'm trying to get the last day of the current month and the last day of the next month. 我想要获得当月的最后一天和下个月的最后一天。

Here's the code I've come up with so far, but I'm forced to mix between NodaTime code and the .NET method DateTime.DaysInMonth() to achieve what I'm looking for, which doesn't sound right. 这是我到目前为止提出的代码,但是我被迫在NodaTime代码和.NET方法DateTime.DaysInMonth()之间混合以实现我正在寻找的东西,这听起来不对。

class Program {

    public static void Main(string[] args)
    {
        DateTimeZone mst = DateTimeZoneProviders.Tzdb["MST"];

        Instant now = SystemClock.Instance.Now;
        ZonedDateTime mstNow = now.InZone(mst);

        LocalDate mstLastDayOfCurrentMonth = new LocalDate(mstNow.Year, mstNow.Month, DateTime.DaysInMonth(mstNow.Year, mstNow.Month));
        Console.WriteLine("Last Day of Current Month: {0}", mstLastDayOfCurrentMonth);

        //move into the next month
        LocalDate nextMonth = mstLastDayOfCurrentMonth.PlusDays(1);
        LocalDate mstLastDayOfNextMonth = new LocalDate(nextMonth.Year, nextMonth.Month, DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month)); 
        Console.WriteLine("Last Day of Next Month: {0}", mstLastDayOfNextMonth);

    }

}

Can you please let me know what is the NodaTime recommended way to get the last day of the current and next months? 你能否告诉我NodaTime推荐的方式来获得当前和下个月的最后一天?

Thanks in advance 提前致谢

Get the Calendar of your ZonedDateTime and then call the GetDaysInMonth(year, month) method: 获取ZonedDateTimeCalendar ,然后调用GetDaysInMonth(year, month)方法:

ZonedDateTime mstNow = now.InZone(mst);
CalendarSystem calendar = mstNow.Calendar;
LocalDate mstLastDayOfCurrentMonth = new LocalDate(
    mstNow.Year, mstNow.Month, calendar.GetDaysInMonth(mstNow.Year, mstNow.Month));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM