2013-01-21 35 views
2

您好我想遍歷日期範圍而不使用任何庫。我想從18/01/2005開始(希望將其格式設置爲yyyy/M/d),並以日間隔進行迭代,直到當前日期。我已經格式化了開始日期,但我不知道如何將它添加到日曆對象並進行迭代。我想知道是否有人可以幫忙。由於迭代通過日期範圍,而無需使用庫 - Java

String newstr = "2005/01/18"; 
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d"); 

回答

6
Date date = format1.parse(newstr); 
Calendar calendar = new GregorianCalendar(); 
calendar.setTime(date); 
while (someCondition(calendar)) { 
    doSomethingWithTheCalendar(calendar); 
    calendar.add(Calendar.DATE, 1); 
} 
1

使用SimpleDateFormat解析字符串轉換成Date對象或格式化Date對象轉換爲字符串。

使用類Calendar進行日期算術。它有一個add方法來推進日曆,例如一天。

請參閱上面提到的類的API文檔。

或者,使用Joda Time庫,這使得這些事情更容易。 (標準Java API中的DateCalendar類有許多設計問題,並沒有Joda Time那麼強大)。

-2

Java,實際上很多系統的存儲時間爲自1970年1月1日中午12:00以來的毫秒數。這個數字可以被定義爲長。

//to get the current date/time as a long use 
long time = System.currentTimeMillis(); 

//then you can create a an instance of the date class from this time. 
Date dateInstance = new Date(time); 

//you can then use your date format object to format the date however you want. 
System.out.println(format1.format(dateInstance)); 

//to increase by a day, notice 1000 ms = 1 second, 60 seconds = 1 minute, 
//60 minutes = 1 hour 24 hours = 1 day so add 1000*60*60*24 
//to the long value representing time. 
time += 1000*60*60*24; 

//now create a new Date instance for this new time value 
Date futureDateInstance = new Date(time); 

//and print out the newly incremented day 
System.out.println(format1.format(futureDateInstance)); 
+0

這不是爲日期添加一天的好方法。由於DST,每天至少有一次會失敗,當天持續25小時。 –

+0

這只是如何增加時間的一個例子,而不是最終的固定解決方案。你可以考慮更多的因素,如果你需要它們 –

+0

和重新實現GregorianCalendar?不,對不起。日期理論很難做到正確。這真是你不想自己做的事情。 –