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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章