如何使用 DateTimeFormatter 或 Java 中的任何其他库将“2019-07-14T18:30:00.000Z”转换为“2021-09-26 04:30:00 PM”

Kir*_*Jha 2 java datetime-format java-time

我不确定这个问题是否已经得到回答,但谁能告诉我如何使用“2019-07-14T18:30:00.000Z”将“2019-07-14 04:30:00 PM”转换为“2019-07-14 04:30:00 PM” DateTimeFormatter 或 Java 中的任何其他库?基本上输出日期时间应该有 AM/PM 格式的时间。

Tah*_*aha 8

尝试这个

String date = "2019-07-14T18:30:00.000Z";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date parsedDate = inputFormat.parse(date);
String formattedDate = outputFormat.format(parsedDate);
System.out.println(formattedDate);
Run Code Online (Sandbox Code Playgroud)

  • 您忽略了“Z”指定特定时区的事实。您需要在解析之前调用`inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));`。 (5认同)

Dea*_*ool 5

通过使用,ZonedDateTime您可以解析输入UTC格式字符串,然后使用LocalDateTimeDateTimeFormatter来格式化输出字符串。但我不确定你在输入和输出字符串中有天、月和时间差异的依据是什么

String date = "2019-07-14T18:30:00.000Z";

ZonedDateTime dateTime = ZonedDateTime.parse(date);

String res = dateTime.withZoneSameInstant(ZoneId.of("//desired zone id")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a"));
Run Code Online (Sandbox Code Playgroud)