gpt4 book ai didi

java - 将长字符串解析为 LocalDate 变量

转载 作者:行者123 更新时间:2023-12-01 19:42:13 26 4
gpt4 key购买 nike

我最近需要获取一个字符串并将其转换为 Java 中的 LocalDate 变量;我知道这是可能且容易的,但这是我没有看到的:

上下文:我正在使用 exiftool 通过 Java 运行时执行从图像中提取元数据。问题是 exiftool 提供了下一个字符串:

2019:02:28 11:37:47-06:00

这不是正常的标准 ISO 格式(或者至少我认为不是)。我不知道这是否使用任何已经实现的格式标准。因此,为了解决我的问题,我创建了下一个用于手动解析的代码:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ssZ", Locale.ENGLISH);
LocalDate date = LocalDate.parse(VAR_WITH_STR_TO_CONVERT, formatter);

我认为这是手动转换的一个很好的实现,但是此代码会生成下一个异常:

> Text '2019:02:28 11:37:47-06:00' could not be parsed at index 19
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)

我相信问题出在我提供的要转换的格式字符串上,但在检查 DateTimeFormatter 文档后,我认为我有正确的字符串。

yyyy:MM:dd HH:mm:ssZ

我没有主意,有人知道这里的问题吗?

最佳答案

TL;DR 对于时区,请使用 XXX 而不是 Z 来解析类似 -06:00< 的值.

<小时/>

文档,即DateTimeFormatter的javadoc ,指定:

Offset X and x: This formats the offset based on the number of pattern letters.

  • One letter outputs just the hour, such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'.
  • Two letters outputs the hour and minute, without a colon, such as '+0130'.
  • Three letters outputs the hour and minute, with a colon, such as '+01:30'.
  • Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'.
  • Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'.
  • Six or more letters throws IllegalArgumentException.

Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.

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.

如您所见,您使用了 1 Z,这意味着 -0600

要解析带有小时和分钟(可选秒)的时区,带有冒号,您需要突出显示的模式之一:

XXX      UTC is `Z`.
XXXXX UTC is `Z`. Optional seconds.
xxx UTC is `+00:00`
xxxxx UTC is `+00:00`. Optional seconds.
ZZZZZ UTC is `Z`. Optional seconds.

关于java - 将长字符串解析为 LocalDate 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54955541/

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