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

LocalDate

使用LocalDate.now()方法来获取当前日期。然后使用isEqual()方法来比较给定日期和当前日期是否相等。

LocalDate date = LocalDate.of(2024, 1, 29);
System.out.println(date.isEqual(LocalDate.now()));

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

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

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

利用SimpleDateFormat

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

直接比较年、月、日

        //判定时间
        LocalDate date = LocalDate.of(2024, 1, 29);
        Date toDate = new Date();
        int year = toDate.getYear();
        int month = toDate.getMonth();
        int day = toDate.getDay();
        int day1 = date.getDay();
        int month1 = date.getMonth();
        int year1 = date.getYear();
        if (year==year1 & month1==month & day==day1){
           //两者时间相等,所以在这里执行特定的代码
        }

你可能感兴趣的:(Java,java,开发语言)