问题背景:
做一个优化需求需要通过时间范围进行搜索。范围是当前时间的前一个小时到当前时间。使用Calendar类来确定范围,但是出现了两个隐藏的问题,一个测试的时候发现了,一个上线后才发现。还好有日志打印(日志打印真的很重要,能够快速帮忙定位问题,发现错误)。
错误1 :[min, max] 是当前时间的前一个小时至当前时间, 这个时间段。 错误主要是使用了calendar.set(Calendar.HOUR, -1); 以为这样就可以设置当前时间减去1。
long max = new Date().getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR, -1);
long min = calendar.getTime().getTime();
其实得到的结果: 其中当前时间是2018-01-12 10:50:06。 -1 得到的根本不是当前时间的前一个小时。
2018-01-11 23:50:06
2018-01-12 10:50:06
查看接口说明:public void set(int field, int value) 设置field字段的值是value。
改成 : calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) - 1);
2018-01-12 10:12:46
2018-01-12 11:12:46
看上去是OK的,但是到下午的时候就会出问题。 因为 Calendar.HOUR 是12小时制的字段。 但是时间戳是24小时制的。所以会出问题。
最后应该改成:
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY )-1);
错误2:对abstract public void add(int field, int amount); 此函数的错误使用。
long max = new Date().getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
long min = calendar.getTime().getTime();
得到的结果
2018-01-13 03:28:12
2018-01-12 14:28:12
注意:public void add(int field, int amount)是field字段加上指定数量的amount 。
明显不是想要的。
对Calendar类的功能详细解析:
Calendar类中字段属性的值:
Calendar类中接口函数的值:
常用的时间工具jar包,省去自己对时间类的手动实现 :
科普:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”) ;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”) ;
其中yyyy-MM-dd HH:mm:ss 指24小时制度输出
yyyy-MM-dd hh:mm:ss 指12小时制度输出
12小时制是跟挂钟时间一致的(分am 和 pm),24小时制是 23:00:00 这种的。