目的:将UTC时间转换为北京时间
Java提供了至少两种时间转换方式,
分别是 SimpleDateFormat 和 DateTimeFormatter
这两者的区别是:
第一种线程不安全,因此每次使用都需要 new 一个新的对象,执行效率较低。
在多线程的场景下如果定义为静态变量被公共使用则会有线程不安全问题;
第二种是Java8新出的功能,避免了线程不安全问题,可以被当做静态变量公共使用;
现使用上述两种方法实现UTC时间转UTC8(北京、上海时间)
上代码
方法1
Date dateUTC = null;
//定义UTC时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
//解析字符串UTC时间Date类型
dateUTC = sdf.parse(timestamp);
}catch (ParseException ignored) {
log.error("UTC time parse failed, UTC time is {}", timestamp);
}
//定义中国上海地区时间格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
return simpleDateFormat.format(dateUTC);
输入 timeStamp为字符串, 输出也为字符串
这里GMT == UTC
方法2
//UTC时间格式
public static final DateTimeFormatter timeFormatForUTC = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
//上海时间格式
public static final DateTimeFormatter timeFormatForChina = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static String conversionTimeFormat(String timestamp) {
LocalDateTime dateUTC = LocalDateTime.parse(timestamp, timeFormatForUTC);
ZonedDateTime dateZoneForUTC = ZonedDateTime.of(dateUTC, ZoneId.of("GMT"));
return timeFormatForChina.format(dateZoneForUTC.withZoneSameInstant(ZoneId.of("Asia/Shanghai")));
}
完成