寫在前頭
最近部門要求代碼要更加嚴格的規範化,使得我有機會接觸到 jdk8 中新增的一些method、class,驚呼NB!
決意就一篇筆記 記錄一下 …
No.1 使用LocateDateTime 設置時間,精確到時分秒
主要功能是在應對某些條件查詢時,需要查詢某個時間範圍符合條件的結果,需要對“結束”時間做一個調整(畢竟前端有時傳給你的只是yyyy-dd-mm,你懂得~~)
之前使用的是Calendar來對時間進行設置,不過存在一定的風險。
話不多說,上代碼~
public static Date changeTime(Date date){
//設置查詢條件的結束時間 時分秒爲當天的23:59:59
// 之前的代碼,會報出“警告”
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
// calendar.set(Calendar.HOUR_OF_DAY, 23);
// calendar.set(Calendar.MINUTE, 59);
// calendar.set(Calendar.SECOND, 59);
// 下邊是JDK8
ZoneId zoneId = ZoneId.systemDefault();
String dateStr = new SimpleDateFormat(Constants.sdf_pattern).format(date);
LocalDateTime time = LocalDateTime.parse(dateStr,DateTimeFormatter.ofPattern(Constants.sdf_pattern));
time = time.withHour(23);
time = time.withMinute(59);
time = time.withSecond(59);
ZonedDateTime zonedDateTime = time.atZone(zoneId);
date = Date.from(zonedDateTime.toInstant());
return date;
}
測試:
@Test
public void testMethod(){
Date date = new Date();
System.out.println("date = " + date);
date = changeTime(date);
System.out.println("date = " + date);
}
結果:
date = Tue Sep 17 11:27:19 CST 2019
date = Tue Sep 17 23:59:59 CST 2019