别看!Java时间字符串传递过程中的时区转换

102 阅读1分钟

背景

在Rest API接口调用中,服务端直接返回包含Date属性的对象结果,客户端在解析后,得到的时间格式为yyyy-MM-dd HH:mm:ss Z形式。此时,时区为GMT。如果直接截取前面不分日期时间都会晕+8区的时间存在8小时偏差。

处理

参考网上已有的方案,并加以测试得到:

// SimpleDateFormat 非线程安全
// 来源格式2023-02-01 00:00:00 +0000
// 北京时间2023-02-01 08:00:00
String s = "2023-02-01 00:00:00 +0000";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
DateFormat df2 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df2.setTimeZone(TimeZone.getTimeZone("GMT+8"));
try{
    Date date = df.parse(s);
    String result = df2.format(date);
    // 2023-02-01 08:00:00
    System.out.println(result);
} catch (ParseException pe){
    pe.printStackTrace();
}
// DateTimeFormatter 线程安全
// 来源格式2023-02-01 00:00:00 +0000
// 北京时间2023-02-01 08:00:00
String s = "2023-02-01 00:00:00 +0000";
LocalDateTime nowLDTime = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormater.ofPatteren("yyyy-MM-dd HH:mm:ss Z");
DateTimeFormatter dtf2 = DateTimeFormater.ofPatteren("yyyy-MM-dd HH:mm:ss");
String result = df2.format(LocalDateTime.parse(s,df));
// 2023-02-01 08:00:00
System.out.println(result);