Java判斷兩個Date是不是同一天

Java判斷兩個Date是不是同一天

1. 利用Calendar

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
    cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);

2. 利用org.apache.commons.lang.time.DateUtils

boolean samedate = DateUtils.isSameDay(date1, date2);  //Takes either Calendar or Date objects

引入了額外的包

3. 利用SimpleDateFormat

SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));

據說這種方法更快。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章