Java Date operation
有關Java Date 相關操作,工作遇到時區轉換的問題,透過此次機會一起統整經過及方法。
前情提要
人狠,話不多,上扣!!
/**
* convert date String with time zone to LocalDateTime Object
*
* @param dateStr
* @param formatterPattern
* @param dateStrTimeZone
* @param toTimeZon
* @return
* @throws ParseException
*/
private static LocalDateTime convertDateStrWithTimeZone(String dateStr, String formatterPattern, TimeZone dateStrTimeZone, ZoneId toTimeZon) throws ParseException {
/**
* 這邊會發生兩件事情
* 1.SimpleDateFormat 認定字串 為 GMT+0
* 2.Date Object 將轉換的GMT+0 加上系統預設時區
* Ex. "2023-03-23 12:00:00" -> 是GMT+0 時區的時間
* 當下系統 default 時區是 GMT+8
* 轉換結果就會變成 2023-03-23 20:00:00[GMT+8]
*/
// Create a SimpleDateFormat object for parsing the date string
SimpleDateFormat sdf = new SimpleDateFormat(formatterPattern);
// Set the time zone of the SimpleDateFormat object to GMT+0
sdf.setTimeZone(dateStrTimeZone);
// Parse the date string into an Instant object and transfer to LocalDataTime
return sdf.parse(dateStr).toInstant().atZone(toTimeZon).toLocalDateTime();
}
/**
* @param dateTime
* @param fromZone
* @param toZone
* @return
*/
private static LocalDateTime convertTimeZoneUseZoneId(LocalDateTime dateTime, ZoneId fromZone, ZoneId toZone) {
ZonedDateTime originZoneDateTime = ZonedDateTime.of(dateTime, fromZone);
ZonedDateTime transZoned = originZoneDateTime.withZoneSameInstant(toZone);
return transZoned.toLocalDateTime();
}
/**
* @param dateTime
* @param fromOffset
* @param toOffset
* @return
*/
public static LocalDateTime convertTimeZoneUseZoneOffset(LocalDateTime dateTime, ZoneOffset fromOffset, ZoneOffset toOffset) {
long timeDifference = toOffset.getTotalSeconds() - fromOffset.getTotalSeconds();
return dateTime.plusSeconds(timeDifference);
}測試!
結論
Last updated