特定格式的java解析字符串到日期
我有一个格式为String stringDate = "2019-04-25T07:03:17.428Z";
的字符串,需要将其转换为格式为2019-04-25 07:03:17的LocalDateTime对象
我已尝试使用LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
,但出现了以下解析异常:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-04-25T07:03:17.428Z' could not be parsed at index 10
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
at com.company.Main.main(Main.java:12)
转换为特定格式的方法是什么
# 1 楼答案
你要求的(但不想要的)
输出为
它给你你所说的你想要的,但是正如rzwitserloot在另一个answer中指出的,它没有意义。它忽略字符串中的偏移量
Z
。偏移量对于将日期和时间解释为时间点至关重要。如果字符串改为2019-04-25T07:03:17.428+13:00
,那么即使字符串表示早13个小时的时间点,您仍然会得到相同的输出对
truncatedTo()
的调用去掉了秒的分数。如果你能忍受那一秒,那就别打电话了你想要什么
对于更合理的转换:
现在UTC时间07:03已转换为中欧夏季时间09:03
编辑:如果您确实需要UTC中的
LocalDateTime
,例如,对于需要它的数据库列,您可以通过以下方式在代码中明确这一事实:你的代码出了什么问题
为了了解失败的原因,让我们看看您收到的异常消息:
索引10是表示时间部分开始的
T
的位置。让我们比较一下您的格式模式字符串:yyyy-MM-dd HH:mm:ss
。它在时间部分之前有一个空格而不是一个T
。这就是例外的原因。如果您需要在模式中指定一个T
必须在那里,我们需要将它括在单引号中,例如yyyy-MM-dd'T'HH:mm:ss
# 2 楼答案
您可以首先使用java解析它。时间即时,然后使用java的即时方法。时间LocalDateTime示例:
# 3 楼答案
基本上,您的输入不是LDT。这是一个ZDT——Z是一个区域(ZoneDateTime)。因此,不可能将这个字符串直接转换为LDT,这很好,因为这没有意义
将其转换为ZDT。然后将的转换为LDT。这是一个单一的方法调用