2012-07-15 83 views
-1

我正在比較java中的2個日曆對象。這種方式我設置他們每個人java日曆比較不正確

Calendar calendar1 = Calendar.getInstance(); 
calendar1.set(2012, 6, 17, 13, 0); 

的,我正從表列「2012-07-17 13:00:00」下面的值,並將其設置爲日期的Java對象,然後此Date對象我正在使用設置第二個Calander對象。

Calendar calendar2 = Calendar.getInstance(); 
calendar2.setTime(/*Above date object who value is '2012-07-17 13:00:00'*/); 

現在,當我比較我希望這是真的,因爲這兩個日曆對象相同

calendar2.compareTo(calendar1) >= 0 

而是我看到這是成爲真正的

calendar2.compareTo(calendar1) < 0 

有人可以幫助?

+1

返回的日曆基於默認語言環境的默認時區中的**當前時間**。 http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#getInstance%28%29 – 2012-07-15 03:10:34

+1

'calendar1.set(2012,6,17,13,0);'only上升到分鐘字段,而秒和毫秒不被設置爲0. – 2012-07-15 03:19:43

+0

那麼我該如何設置第二個廣告毫秒? – user1241438 2012-07-15 03:37:32

回答

1

下面將爲你發生了什麼事情(假設你解析字符串來產生calendar1日期對象)的想法:

Calendar calendar1 = Calendar.getInstance(); 
calendar1.set(2012, 6, 17, 13, 0); 
System.out.println(calendar1.getTime()); 
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-07-17 13:00:00"); 
System.out.println(date); 
Calendar calendar2 = Calendar.getInstance(); 
calendar2.setTime(date); 
System.out.println(calendar2.compareTo(calendar1)); 
calendar1.set(Calendar.SECOND, 0); //setting second to 0 
calendar1.set(Calendar.MILLISECOND, 0); //setting millisecond to 0 
System.out.println(calendar2.compareTo(calendar1)); 

試運行結果:

 
Tue Jul 17 13:00:47 CDT 2012 
Tue Jul 17 13:00:00 CDT 2012 
-1 
0 
0

經過@Bhesh Gurung的建議,我使用了以下內容:

calendar1.set(Calendar.MILLISECOND,0); calendar1.set(Calendar.SECOND,0);

calendar2.set(Calendar.MILLISECOND,0); calendar2.set(Calendar.SECOND,0);

它工作。