有多种方法可以判断两个Java Date类型是否是同一天,以下是其中的几种常用方法:

  1. 使用SimpleDateFormat类将日期格式化为“yyyy-MM-dd”字符串,然后比较字符串是否相等。
Date date1 = new Date();
Date date2 = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str1 = sdf.format(date1);
String str2 = sdf.format(date2);

if (str1.equals(str2)) {
    // 两个日期是同一天
}
  1. 使用Calendar类获取日期的年、月、日,然后比较是否相等。
Date date1 = new Date();
Date date2 = new Date();

Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
int year1 = cal1.get(Calendar.YEAR);
int month1 = cal1.get(Calendar.MONTH);
int day1 = cal1.get(Calendar.DAY_OF_MONTH);

Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int year2 = cal2.get(Calendar.YEAR);
int month2 = cal2.get(Calendar.MONTH);
int day2 = cal2.get(Calendar.DAY_OF_MONTH);

if (year1 == year2 && month1 == month2 && day1 == day2) {
    // 两个日期是同一天
}
  1. 使用TimeUnit类计算两个日期间的天数差,如果差为0则表示是同一天。
Date date1 = new Date();
Date date2 = new Date();

long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);

if (diffDays == 0) {
    // 两个日期是同一天
}
``
Java两个Date类型如何判断是否是同一天

原文地址: https://www.cveoy.top/t/topic/gCqJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录