使用場(chǎng)景:redis緩存,需要設(shè)置 鍵-值 的過期時(shí)間.往往我們會(huì)使用當(dāng)前問題。。
使用方法:方案一: 使用Calendar(Java 8之前)
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;
}
方案二:使用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;
}
兩者區(qū)別:使用LocalDateTime提供的對(duì)象是不可改變并且線程安全的
Calendar是線程非安全的,多線程情形下需要注意。
本站文章版權(quán)歸原作者及原出處所有 。內(nèi)容為作者個(gè)人觀點(diǎn), 并不代表本站贊同其觀點(diǎn)和對(duì)其真實(shí)性負(fù)責(zé),本站只提供參考并不構(gòu)成任何投資及應(yīng)用建議。本站是一個(gè)個(gè)人學(xué)習(xí)交流的平臺(tái),網(wǎng)站上部分文章為轉(zhuǎn)載,并不用于任何商業(yè)目的,我們已經(jīng)盡可能的對(duì)作者和來源進(jìn)行了通告,但是能力有限或疏忽,造成漏登,請(qǐng)及時(shí)聯(lián)系我們,我們將根據(jù)著作權(quán)人的要求,立即更正或者刪除有關(guān)內(nèi)容。本站擁有對(duì)此聲明的最終解釋權(quán)。