gpt4 book ai didi

java - 解析日期的正确方法

转载 作者:行者123 更新时间:2023-12-02 01:10:58 25 4
gpt4 key购买 nike

我正在尝试解析以下日期,但出现运行时错误:

java.time.format.DateTimeParseException: Text '2019-11-21-05:00' could not be parsed, unparsed text found at index 10

我的输入:

String inpDate = "2019-11-20-05:00"

我还尝试了以下日期格式,但没有成功。

yyyy-MM-ddZ

yyyy-MM-dd Z

代码:

public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(DATE_FORMAT);

LocalDate localDate = LocalDate.parse(inpDate, dateFormatter);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

如何正确解析我的输入?

最佳答案

使用以下格式:

public static final String DATE_FORMAT = "yyyy-MM-ddZZZZZ";

它有 5 倍的字母“Z”。要使用冒号解析时区偏移量,您需要提供字母“Z”5 次。这可能在某种程度上隐藏在 Javadoc 中。

来自Javadoc :

Offset Z: This formats the offset based on the number of pattern letters.

One, two or three letters outputs the hour and minute, without a colon, such as '+0130'. The output will be '+0000' when the offset is zero.

Four letters outputs the full form of localized offset, equivalent to four letters of Offset-O. The output will be the corresponding localized offset text if the offset is zero.

Five letters outputs the hour, minute, with optional second if non-zero, with colon.

It outputs 'Z' if the offset is zero. Six or more letters throws IllegalArgumentException.

关于java - 解析日期的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com