实际项目开发过程中我们需要设置某个redis的key只保留一天,如刷新时间日期的key

redisTemplate.opsForValue().set(CHARGEBI_YEAR_WEEKS, "2022-04-25",seconds, TimeUnit.SECONDS);

所以我们在设置的key的时候就需要计算当前时间离凌晨的秒数

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

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

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其中之一

 public static Integer getRemainSecondsOneDay(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;
    }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐