我有兩個Date
s。我怎樣才能在幾天內分辨這兩個日期之間的差異?我曾聽說過SimpleDateFormat
,但我不知道如何使用它。如何查找兩個日期之間的天數?
我嘗試這樣做:
String fromdate = "Apr 10 2011";
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("MMM DD YYYY");
sdf.parse(fromdate);
Calendar cal = Calendar.getInstance();
cal.setTime(sdf);
我也試過這樣:
String date1 = "APR 11 2011";
String date2 = "JUN 02 2011";
String format = "MMM DD YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff/(24* 1000 * 60 * 60));
System.out.println(diffDays);
,但我得到了異常 「非法字符模式 'Y'。」
你說的*區別意味着*?你想測試哪一個更及時,或者你只是想知道它們是不同的? – 2011-06-02 18:49:10
請參閱http://stackoverflow.com/questions/5497762/find-time-differnce和http://stackoverflow.com/questions/5194216/how-can-i-calculate-the-difference-between-two-dates和http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java – x4u 2011-06-02 18:49:45
什麼區別?毫秒?天?天,小時,分鐘?等等請注意'DD'和'YYYY'是幾天和幾年的無效模式。閱讀javadoc:http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html – BalusC 2011-06-02 18:50:47