String time type is converted to ZonedDateTime time type

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:

  1. 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.
  2. Use the parse method in DateTimeFormatter to parse string into DateTimematter format

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325727001&siteId=291194637