I've been working on it all morning and don't know how to do this. In the end, I found that it is not necessary to write ZonedDateTime completely, it can be simplified and packaged
public static ZonedDateTime changeShanghaiToUTC(String beijingDateTimeStr){
DateTimeFormatter beijingFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));
if(StringUtils.isBlank(beijingDateTimeStr)){
return null;
}
ZonedDateTime beijingDateTime = ZonedDateTime.parse(beijingDateTimeStr, beijingFormatter);
return beijingDateTime.withZoneSameInstant(ZoneId.of("UTC"));
}
key point:
- Add the value of withZone after DateTimeFormatter. It is necessary to convert String to ZonedDateTime, otherwise an error will be reported when converting to string.
- Use the parse method in DateTimeFormatter to parse string into DateTimematter format