2014-02-14 121 views
3

我正在嘗試獲取當前月份的最後一天和下個月的最後一天。如何獲取當前月份的最後一天和下個月的最後一天

以下是我到目前爲止所使用的代碼,但是我不得不在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); 

    } 

} 

您能否讓我知道NodaTime推薦的方式是什麼,以獲得當前和未來幾個月的最後一天?

在此先感謝

回答

6

讓您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)); 
+0

不知道我怎麼錯過了,但它的作品太好了,謝謝。 – FullOfQuestions

相關問題