假設我有兩個日期,如下所示。比較日期,忽略Joda中DateTime的秒和毫秒瞬間
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45");
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45");
我想這兩個日期比較一下,看是否firstDate
遲早是,以後或等於secondDate
。
我可以試試以下內容。
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isBefore(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isAfter(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.equals(secondDate));
這段代碼產生了什麼正是我想要的。
它產生以下輸出。
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = true
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false
我需要忽略秒和這些日期的毫秒部分。我試圖使用如下的withSecondOfMinute(0)
和withMillis(0)
方法。
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45").withSecondOfMinute(0).withMillis(0);
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45").withSecondOfMinute(0).withMillis(0);
但它產生了以下輸出。
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = true
withSecondOfMinute()
方法描述的文檔。
返回此日期時間的副本,並更新第二分鐘字段 。 DateTime是不可變的,所以沒有設置方法。取而代之, 此方法返回一個新實例,其值爲第 秒的值更改。
而方法withMillis()
的文檔說。
返回不同毫秒的日期時間的副本。返回的 對象將成爲新實例或此對象。只有毫米將 改變,年表和時區保留。
完全忽略時間部分比較日期可以很容易地使用大致如下的DateTimeComparator.getDateOnlyInstance()
來完成。
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)==0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)<0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)>0){}
如何比較兩個日期忽略DateTime
特定時刻(秒和毫秒在這種情況下)?
非常感謝。完成! – Tiny 2013-02-18 23:42:29
@微小。不客氣:) – 2013-02-18 23:46:08