使用SimpleDateFormat獲取指定時(shí)區(qū)時(shí)間
摘要:使用SimpleDateFormat把時(shí)間戳轉(zhuǎn)換成指定格式的、指定時(shí)區(qū)的字符串。
??SimpleDateFormat是Java中的一個(gè)日期格式化類,繼承了DateFormat,可以實(shí)現(xiàn)日期時(shí)間和時(shí)間字符串的相互轉(zhuǎn)換。為了把時(shí)間正確地轉(zhuǎn)換成時(shí)間字符串,我們需要考慮當(dāng)前所在時(shí)區(qū),而SimpleDateFormat可以通過(guò)繼承的方法setTimeZone(TimeZone zone)設(shè)置時(shí)區(qū):
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 設(shè)置時(shí)區(qū)為東七區(qū)
sdf.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
??在日期時(shí)間格式化時(shí),通常使用的模式字符串為"yyyy-MM-dd HH:mm:ss",代碼示例如下:
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Instant now = Instant.now();
System.out.println("與時(shí)區(qū)無(wú)瓜葛的時(shí)間戳:" + now.toEpochMilli());
Date current = Date.from(now);
System.out.println("本地時(shí)間:" + sdf.format(current));
// 設(shè)置UTC時(shí)區(qū)
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// UTC時(shí)間比北京時(shí)間少八個(gè)小時(shí)
System.out.println("SimpleDateFormat UTC時(shí)間:" + sdf.format(current));
sdf.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
System.out.println("GMT+7 時(shí)間:" + sdf.format(current));
}
執(zhí)行結(jié)果如下:
與時(shí)區(qū)無(wú)瓜葛的時(shí)間戳:1691906288129
本地時(shí)間:2023-08-13 13:58:08
SimpleDateFormat UTC時(shí)間:2023-08-13 05:58:08
GMT+7 時(shí)間:2023-08-13 12:58:08
??sdf.format(current)是把時(shí)間戳轉(zhuǎn)換成指定格式的、指定時(shí)區(qū)的字符串。
讀后有收獲,小禮物走一走,請(qǐng)作者喝咖啡。
Buy me a coffee. ?Get red packets.作者:樓蘭胡楊
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但請(qǐng)注明原文鏈接,并保留此段聲明,否則保留追究法律責(zé)任的權(quán)利。

浙公網(wǎng)安備 33010602011771號(hào)