判断给定的时间是否在某个日期区间内

该博客主要介绍了如何使用Java的SimpleDateFormat进行日期格式化,将当前时间与指定日期进行比较,判断当前时间是否在给定的时间区间内。示例代码展示了如何创建日期对象,进行时间格式化和解析,并实现了一个有效日期判断的方法。此内容对于理解和操作Java日期时间有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 String format = "yyyy-MM-dd hh:mm:ss";
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
 Date date = new Date(System.currentTimeMillis());
 String today = simpleDateFormat.format(date);
 Date nowTime = simpleDateFormat.parse(today);
 Date startDate = simpleDateFormat.parse(“日期”);
 Date endDate = simpleDateFormat.parse(“日期”);
    /**
     * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     *
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值