首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >实现redis缓存次日凌晨失效

实现redis缓存次日凌晨失效

作者头像
adu
发布2022-10-30 15:00:10
发布2022-10-30 15:00:10
1.2K0
举报
文章被收录于专栏:adu_blogadu_blog

思路

实际项目开发过程中我们需要设置某个redis的key只保留一天,如刷新时间日期的key,所以我们在设置的key的时候就需要计算当前时间离凌晨的秒数

方案一:使用Calendar(Java 8之前)

getInstance()是Calendar提供的一个类方法,它的作用是获得一个Calendar类型的通用对象,getInstance()将返回一个Calendar的对象。使用Calendar.getInstance()不仅能获取当前的时间,还能指定需要获取的时间点。

代码语言:javascript
复制
public static Integer getRemainSecondsOneDay(Date currentDate) {
        Calendar midnight=Calendar.getInstance();
        midnight.setTime(currentDate);
        midnight.add(midnight.DAY_OF_MONTH,1);//将日加1
        midnight.set(midnight.HOUR_OF_DAY,0);//控制时
        midnight.set(midnight.MINUTE,0);//控制分
        midnight.set(midnight.SECOND,0);//控制秒
        midnight.set(midnight.MILLISECOND,0);//毫秒
        //通过以上操作就得到了一个currentDate明天的0时0分0秒的Calendar对象,然后相减即可得到到明天0时0点0分0秒的时间差
        Integer seconds=(int)((midnight.getTime().getTime()-currentDate.getTime())/1000);
        return seconds;
    }

方案二:java8之后,我们可以使用LocalDateTime

Java8推出了线程安全、简易、高可靠的时间包,LocalDateTime其中之一

代码语言:javascript
复制
public static Integer getRemainSecondsOneDays(Date currentDate) {
        //使用plusDays加传入的时间加1天,将时分秒设置成0
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
                .withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault());
        //使用ChronoUnit.SECONDS.between方法,传入两个LocalDateTime对象即可得到相差的秒数
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }

测试

代码语言:javascript
复制
    public static void main(String[] args) {
//        int time = ComputationTimeUtils.getRemainSecondsOneDay(new Date());
        int time = ComputationTimeUtils.getRemainSecondsOneDays(new Date());
        System.err.println(time);
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022/08/10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档