2015-03-31 58 views
1

如何在Joda時間的循環中獲得本月的第15天和最後一天?Joda時間操作獲得月的第15天和最後一天

這是代碼的樣子:

DateTime initDate = new DateTime(2015,1,31,0,0); 

for(int i = 0; i > 4; i++){ 
    initDate = initDate.plusDays(15); 

    System.out.println(initDate.toString("yyyy-MM-dd"); 
} 

我只是希望得到的結果是這樣的:

2015-2-15 
2015-2-28 
2015-3-15 
2015-3-30 
+0

這肯定會幫助:http://stackoverflow.com/questions/9711454/how-to-get-the-last-date-of-a-特別的月份與喬丹時間 – ochi 2015-04-01 00:20:40

回答

2
for(int i = 0; i < 4; i++){ 
      initDate = initDate.plusMonths(1); 
      initDate = initDate.withDayOfMonth(15); 
      System.out.println(initDate.toString("yyyy-MM-dd")); 
      System.out.println(initDate.dayOfMonth().withMaximumValue().toString("yyyy-MM-dd")); 
     } 

這樣的事情?

+0

可能不會做你認爲它的作用。畢竟,2月份的最大值是29日,這隻有25%的時間是正確的。 – 2015-04-01 00:23:05

+0

謝謝先生。它確實有很大的幫助。 – 2015-04-01 02:33:32

+0

請將我的答案標記爲已接受。 – 2015-04-01 06:18:41

0

您無法通過添加固定天數來獲取每月的最後一天,因爲所有月份的天數都不相同。

相反,使用你的循環,像這樣

for (each month) { 
    set the month appropriately (set not add) 
    get the 15th day of this month (set not add) 
    print the 15th day 
    set the next month 
    set the 1st day of the "next" month 
    subtract a day 
    print the "last" day 
} 
相關問題