Java判断两个Date是不是同一天

版权声明:本文为博主原创文章,转载请联系作者取得授权。 https://blog.csdn.net/xingchenbingbuyu/article/details/82734695

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));

据说这种方法更快。

猜你喜欢

转载自blog.csdn.net/xingchenbingbuyu/article/details/82734695