使用java.time解析没有’T’分隔符的日期时间字符串。

huangapple go评论70阅读模式
英文:

Parse a datetime string that has no 'T' separator using java.time

问题

我正在尝试使用java.time库将字符串“2023-05-10 09:41:00”解析为LocalTime。

当我尝试使用LocalTime.parse("2023-05-10 09:41:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME)时,我得到java.time.format.DateTimeParseException异常。然而,当我尝试使用LocalTime.parse("2023-05-10T09:41:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME)时,它可以正常工作。

是否有任何DateTimeFormatter常量可以在没有“T”分隔符的情况下使用?我知道我可以使用自定义的DateTimeFormatter,但我想使用java或kotlin库中的预定义常量,就像伪代码中的DateTimeFormatter.ISO_LOCAL_DATE_TIME_WIHOUT_T一样。

英文:

I am trying to parse string "2023-05-10 09:41:00" to LocalTime using java.time library.

When I try LocalTime.parse("2023-05-10 09:41:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME) I get java.time.format.DateTimeParseException. However when I try LocalTime.parse("2023-05-10T09:41:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME) it works.

Is there any DateTimeFormatter constant I can use that works without the "T" separator? I am aware I can use a custom DateTimeFormatter but I would like to use a prepackaged constant from java or kotlin library like pseudo code DateTimeFormatter.ISO_LOCAL_DATE_TIME_WIHOUT_T.

答案1

得分: 1

> 有没有可以在没有"T"分隔符的情况下使用的DateTimeFormatter常量?

没有,因为java.time基于ISO 8601,它使用带有"T"作为时间分隔符的日期时间字符串。

但是,您可以使用一些技巧来实现它(仅供娱乐,不适用于生产代码)。

演示

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2023-05-10 09:41:00";
        ParsePosition position = new ParsePosition(strDateTime.indexOf(' ') + 1);
        LocalTime time = LocalTime.from(DateTimeFormatter.ISO_LOCAL_TIME.parse(strDateTime, position));
        System.out.println(time);
    }
}

输出:

09:41

还有另一个技巧,Ole V.V. 已经在他的评论中提到了。

<kbd>ONLINE DEMO</kbd>

从**Trail: Date Time**了解更多关于现代日期时间API的信息。

英文:

> Is there any DateTimeFormatter constant I can use that works without
> the "T" separator?

There is none because java.time is based on ISO 8601 which uses a date-time string with T as the time separator.

However, you can achieve it with some hacks (just for fun, not for production code).

Demo

public class Main {
    public static void main(String[] args) {
        String strDateTime = &quot;2023-05-10 09:41:00&quot;;
        ParsePosition position = new ParsePosition(strDateTime.indexOf(&#39; &#39;) + 1);
        LocalTime time = LocalTime.from(DateTimeFormatter.ISO_LOCAL_TIME.parse(strDateTime, position));
        System.out.println(time);
    }
}

Output:

09:41

There is another hack which Ole V.V. has already mentioned in his comment.

<kbd>ONLINE DEMO</kbd>

Learn more about the modern Date-Time API from Trail: Date Time.

huangapple
  • 本文由 发表于 2023年5月10日 22:45:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定