判断一个时间是否在一个时间段内(精确到时分秒)

本文介绍了一种判断当前时间是否在指定时间段内的方法,并提供了将字符串转换为日期格式的实用函数。通过具体示例展示了如何使用这些函数来确定时间是否有效。

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

/**
     * 判断时间是否在时间段内
     * 
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if (date.after(begin) && date.before(end)) {
            return true;
        } else if (nowTime.compareTo(beginTime) == 0 || nowTime.compareTo(endTime) == 0) {
            return true;
        } else {
            return false;
        }
    }
 
    
 
    // 字符串 转 日期
    public static Date strToDate(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
        }
        return date;
    }
    
    public static void main(String[] args) {
        // 生效时间
        Date effectivetime = strToDate("2018-7-8 17:00:00");
        // 失效时间
        Date invalidtime = strToDate("2018-9-8 17:30:00");
        boolean flag = belongCalendar(new Date(), effectivetime, invalidtime);
        System.out.println(flag);
 
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值