2014-02-25 32 views
0

我必須在特定日期範圍內爲每個月的每一天創建表(例如,2012-01-30至2013-04-30) 。我正在嘗試使用三個for循環和DateTime isBefore方法來完成此操作,但是我的循環無限運行(儘管日期,月份和年份按其預期方式遞增)。我下面寫的代碼片段,Java Joda - 嘗試遍歷日期,月份和年份時的無限次迭代

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); 
DateTime startDate = dtf.parseDateTime(startDateTime); 
DateTime endDate = dtf.parseDateTime(endDateTime); 
try{ 

    for(DateTime y=startDate;y.isBefore(endDate);y=y.plusYears(1)) { 
     for(DateTime month=startDate;startDate.isBefore(endDate);month=month.plusMonths(1)) { 
      for(DateTime date=startDate;startDate.isBefore(endDate);date=date.plusDays(1)){ 
       String sqlStmt = "CREATE TABLE IF NOT EXISTS... 
       ... 
      } 
     } 
    } 
} catch (SQLException e) { 

StackTraceElement stack = e.getStackTrace()[2]; 

    } 

我的表越來越創建爲我多麼希望他們所以與我試圖執行sqlstmt沒有問題,只是循環不一旦遇到endDate就終止。我是Java新手,所以不太確定我在這裏做錯了什麼。任何建議將真正有幫助!

謝謝!

回答

5

這不是你的問題嗎?

for(DateTime month=startDate;startDate.isBefore(endDate);month=month.plusMonths(1)) { 

你遞增month,但比較startDate的價值,這不會改變。

我不太清楚你想要達到的目標,但是Joda應該允許你在幾天,幾周,幾個月等內迭代,只需要在初始日期添加一天(plusDays(1))即可。

+0

就像你剛纔提到的,事實證明,我並不需要for循環的一年和一個月(新手錯誤!!!)。所以我刪除它們,並使用date.isBefore而不是startDate.isBefore迭代我的日期循環,並且它完美地工作。非常感謝! – MM2

相關問題