首页 > 解决方案 > 转换为日期时间格式“2020-02-11T17:26:31-05:00”

问题描述

嗨,我无法理解我们需要使用什么时间格式来解析这个日期2020-02-11T17:26:31-05:00 我尝试使用日期格式化程序和简单的日期格式,但它不起作用

日期以这种形式出现 -> 2020-02-11T17:26:31-05:00我无法识别此日期的类型

下面是我尝试过的代码片段,但它抛出异常

DateTimeFormatter responseFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss-SSSXXX'Z'",
                              Locale.ENGLISH);
                     responseDateTime = LocalDateTime.parse(otmmResponseDate, responseFormatter);

标签: javadatetime-format

解决方案


请注意,您的日期字符串中有一个偏移量-05:00。因此,您的字符串不代表 a LocalDateTime,而是 a OffsetDateTime,并且应该被解析OffsetDateTime.parse(并非所有内容都是 a LocalDateTime!):

// the format is ISO 8601, so it can be parsed directly without a DateTimeFormatter
OffsetDateTime odt = OffsetDateTime.parse("2020-02-11T17:26:31-05:00");

如果您只想要其中的本地日期时间部分,那么您可以toLocalDateTime稍后调用:

LocalDateTime ldt = odt.toLocalDateTime();

推荐阅读