使用Calendar遇到的坑

本文介绍了在使用Calendar进行时间判断时遇到的问题。当判断某个不跨天时间段是否在当天,错误地使用了Calendar.HOUR,导致下午时段获取的时间范围包含了次日12点。解决方法是使用Calendar.HOUR_OF_DAY,它是24小时制,能正确获取全天时间。

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

Calendar.HOUR和Calendar.HOUR_OF_DAY

  • 背景:需要判断某个时间段(该时间段不会跨天)是否在当天,于是用到Calender获取当天的开始和结束时间。
    错误使用如下:
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR, 0); // 此处错误
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
Long todayStart = todayStart.getTimeInMillis();
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR, 23); // 此处错误
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
Long todayEnd = todayEnd.getTimeInMillis();

在当天0-12点获取到的时间戳和转出得时间如下,可以看到没有问题。

上午运行HOUR代码

而从12点到24点之间使用上述代码获取到的时间戳和转出得到的时间如下,可以看到下午运行得到的是当天12点到隔天12点的时间。

下午运行HOUR代码

也就是说,这种使用方法在上午是没有问题的,只有到下午才会触发bug,由于测试是在上午测试的(需求很简单,测的时间比较短),没有排查到问题,于是在上线之后的下午发现数据异常,导致了线上bug,第一次遇到线上bug,可紧张了呢T_T

看Calendar对HOUR和HOUR_OF_DAY的注释:

/**
     * Field number for <code>get</code> and <code>set</code> indicating the
     * hour of the morning or afternoon. <code>HOUR</code> is used for the
     * 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12.
     * E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
     *
     * @see #AM_PM
     * @see #HOUR_OF_DAY
     */
    public final static int HOUR = 10;

    /**
     * Field number for <code>get</code> and <code>set</code> indicating the
     * hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
     * E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
     *
     * @see #HOUR
     */
    public final static int HOUR_OF_DAY = 11;

也就是HOUR是12小时制的,HOUR_OF_DAY是24小时制的,使用HOUR_OF_DAY才是正确的使用方式。

以下是正确使用姿势:

Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, 0); // 此处正确
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
Long todayStart = todayStart.getTimeInMillis();
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR_OF_DAY, 23); // 此处正确
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
Long todayEnd = todayEnd.getTimeInMillis();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值