LocalDateTime與時間戳、日期字符串的轉換
摘要:介紹LocalDateTime與時間戳、日期字符串的轉換。
需求背景
??服務器部署在不同時區,數據在業務使用過程中,需要進行時區切換,為了不影響數據效果,把各個時區的時間統一為UTC時區。故分享如何實現LocalDateTime與時間戳、日期字符串的轉換。
LocalDateTime轉字符串
??可以把LocalDateTime轉換成指定時區、指定格式的字符串,以UTC時區為例,轉換成yyyy-MM-dd HH:mm:ss的實現邏輯如下:
private static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static ZoneId myZone = TimeZone.getTimeZone("UTC").toZoneId();
private static ZoneId currentZone = OffsetDateTime.now().getOffset();
/**
* 格式化 LocalDateTime 為UTC時區的字符串
*
* @param localTime
* @return utc 時間
* @Date 2023-08-05
**/
public static String getGivenZoneTimeStr(LocalDateTime localTime) {
// System.out.println("轉換前的時間:" + localTime.format(df));
LocalDateTime newTime = localTime.atZone(currentZone).withZoneSameInstant(myZone).toLocalDateTime();
return newTime.format(df);
}
??如果把myZone換成其它時區,則可以得到對應時區的時間,諸如GMT+7:00、GMT+8:00等。
LocalDateTime轉時間戳
??這篇文章很水,如果不是因為使用如下LocalDateTime轉時間戳導致轉換失敗,也就不發此文了:
public static long local2Timestamp(LocalDateTime localTime) {
// 設置時區偏移量,這里設置為UTC
long milliSecond = localTime.toInstant(ZoneOffset.UTC).toEpochMilli();
System.out.println("local時間轉UTC時間戳:" + milliSecond);
return milliSecond;
}
正確的LocalDateTime轉時間戳實現代碼如下:
/**
* UTC時區
*/
private static ZoneId myZone = TimeZone.getTimeZone("UTC").toZoneId();
private static ZoneId currentZone = OffsetDateTime.now().getOffset();
public static long local2TimestampPlus(LocalDateTime localTime) {
LocalDateTime newTime = localTime.atZone(currentZone).withZoneSameInstant(myZone).toLocalDateTime();
return newTime.toInstant(ZoneOffset.UTC).toEpochMilli();
}
時間戳轉LocalDateTime
這個就簡單了,請各位使用的時候根據需要設置一下時區,我這里使用默認時區驗證:
public static LocalDateTime timestamp2Local(long timestamp) {
return Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
時間戳轉日期字符串
??Date對象保存的是毫秒數,本身不帶時區信息。但是如果調用Date.toString()、Date.parse()等方法把Date展現出來時,就會存在時區的概念,需要進行時區轉換,而且不是所有人都只想要UTC時間。
public static void main(String[] args) {
String result = timestamp2Str(Instant.now().toEpochMilli(), "GMT+7:00");
System.out.println(result);
}
public static String timestamp2Str(long timestamp, String timeZoneId) {
Date timeStampDate = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone(timeZoneId));
return sdf.format(timeStampDate);
}
結束語
??文章到這里就結束了,看完之后你有什么想法想要跟大家分享呢?評論區在等著你!
讀后有收獲,小禮物走一走,請作者喝咖啡。
Buy me a coffee. ?Get red packets.作者:樓蘭胡楊
本文版權歸作者和博客園共有,歡迎轉載,但請注明原文鏈接,并保留此段聲明,否則保留追究法律責任的權利。

浙公網安備 33010602011771號