java.time.format.DateTimeParseException:无法解析文本“2021-02-19T00:45:09.798Z”,在索引23处找到未解析的文本
我是 Java 新手,我不明白我的日期解析有什么问题。我已经尝试了许多类似帖子的解决方案,阅读了 DateTimeFormatter 文档,但仍然卡住了。任何帮助表示赞赏。谢谢你。
代码
String date = "2021-02-19T00:45:09.798Z"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSZ");
ZonedDateTime parsedDate = ZonedDateTime.parse(date, formatter);
错误
java.time.format.DateTimeParseException: Text '2021-02-19T00:45:09.798Z' could not be parsed, unparsed text found at index 23
我也尝试使用DateTimeFormatter.ofPattern(pattern).withZone(zone)并收到相同的错误。
回答
您不需要格式化程序来解析给定的日期时间字符串,因为它已经符合ZoneDateTime#parse预期的默认格式。
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
String date = "2021-02-19T00:45:09.798Z";
ZonedDateTime parsedDate = ZonedDateTime.parse(date);
System.out.println(parsedDate);
}
}
输出:
2021-02-19T00:45:09.798Z
从Trail: Date Time 中了解有关现代日期时间 API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和您的 Android API 工作级别仍然不符合 Java-8,请检查通过 desugaring和How to use ThreeTenABP in Android Project可用的 Java 8+ APIs。
- Since there is no time zone present, I would use `Instant` or `OffsetDateTime` here rather than `ZonedDateTime`.
- @VGR UTC/Zulu is *not* actually a time zone. It is the baseline against which all time zones are defined. That is why the *java.time* provides the `Instant` and `OffsetDateTime` classes separate from `ZonedDateTime`, and why the constant `UTC` is defined on the `ZoneOffset` class rather than on the `ZoneId` class. An offset is merely a number of hours-minutes-seconds, positive or negative. A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by he people of a particular region. So for this Answer, `ZonedDateTime` is inappropriate.
- To be fair, there's also `DateTimeFormatter.ISO_INSTANT` which supports `Z` and Z only, expecting an Instant, always. So depending on what kinds of input OP actually expects, an `Instant` could be a choice (next to `ZonedDateTime` and `OffsetDateTime`), I do not think we can really tell from the single available input. But: Z _usually_ means offset, not ZoneId, even though it's a fine ZoneId, too.
THE END
二维码