你的格式不正确。您在该月使用mm
, 而不是MM
,。此外,您错过了格式中的文字T
。请注意,您需要使用HH
24 小时格式时间。
由于您的日期时间字符串没有时区信息,因此您必须将日期时间字符串解析为LocalDateTime
,然后LocalDateTime#atZone
将其转换为ZonedDateTime
(如果需要ZonedDateTime
),如下所示:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dateString = "2020-09-02T12:22:53.9";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-dd-MM'T'HH:mm:ss.S");
String tz = "America/Mexico_City";
ZoneId zoneId = ZoneId.of(tz);
// Parse the given date-time string to LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(dateString, dtf);
// Convert the LocalDateTime to ZonedDateTime
ZonedDateTime dateTimeInTz = ldt.atZone(zoneId);
// Display ZonedDateTime in its default format
System.out.println(dateTimeInTz);
// Display ZonedDateTime in your custom format
System.out.println(dateTimeInTz.format(dtf));
}
}
输出:
2020-02-09T12:22:53.900-06:00[America/Mexico_City]
2020-09-02T12:22:53.9
或者,您可以使用ZoneId
withDateTimeFormatter
本身,然后您可以将给定的日期时间字符串直接解析ZonedDateTime
为如下所示:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dateString = "2020-09-02T12:22:53.9";
String tz = "America/Mexico_City";
ZoneId zoneId = ZoneId.of(tz);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-dd-MM'T'HH:mm:ss.S").withZone(ZoneId.of(tz));
// Parse the given date-time string into ZonedDateTime
ZonedDateTime dateTimeInTz = ZonedDateTime.parse(dateString, dtf);
// Display ZonedDateTime in its default format
System.out.println(dateTimeInTz);
// Display ZonedDateTime in your custom format
System.out.println(dateTimeInTz.format(dtf));
}
}
输出:
2020-02-09T12:22:53.900-06:00[America/Mexico_City]
2020-09-02T12:22:53.9