java获取当前时间离一天结束剩余秒数

  在使用redis缓存的场景中,往往需要设置 键-值 的过期时间,我们在项目中遇到需要获得当前时间点离当前天结束剩余的秒数作为存储到redis的 键-值 的过期时间。改时间通过java生成,下面提供几种方案供读者参考:

方案一 使用Calendar

Calendar类作为java 8之前描述时间的util类,提供了大量的方法,用于时间的操作,使用Calendar计算剩余秒数:

    public static Integer getRemainSecondsOneDay(Date currentDate) {
        Calendar midnight=Calendar.getInstance();
        midnight.setTime(currentDate);
        midnight.add(midnight.DAY_OF_MONTH,1);
        midnight.set(midnight.HOUR_OF_DAY,0);
        midnight.set(midnight.MINUTE,0);
        midnight.set(midnight.SECOND,0);
        midnight.set(midnight.MILLISECOND,0);
        Integer seconds=(int)((midnight.getTime().getTime()-currentDate.getTime())/1000);
        return seconds;
    }

但是需要注意Calendar是线程非安全的,多线程情形下需要注意。

方案二 使用LocalDateTime

LocalDateTime是java 8的新特性,提供对时间日期的描述和操作,其提供的对象是不可改变并且线程安全的。

public static Integer getRemainSecondsOneDay(Date currentDate) {
        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());
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章