英文:
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. 已经在他的评论中提到了。
从**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 = "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);
}
}
Output:
09:41
There is another hack which Ole V.V. has already mentioned in his comment.
Learn more about the modern Date-Time API from Trail: Date Time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论