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

本文介绍了如何在Java中使用LocalDate类的isEqual()方法,以及ApacheCommonsLang库的DateUtils.isSameDay()方法,Calendar和SimpleDateFormat进行日期比较,以及直接比较年、月、日的示例。
摘要由CSDN通过智能技术生成

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){
           //两者时间相等,所以在这里执行特定的代码
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

strggle_bin

一毛不嫌少,十元不嫌多

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值