【发布时间】:2018-05-18 14:38:44
【问题描述】:
我想将字符串转换为 OffsetDateTime 数据类型。该字符串具有以下形状:
2017-11-27T19:06:03
我尝试了两种方法:
方法 1
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter formatter = new java.time.format.DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
return OffsetDateTime.parse(timestamp, formatter);
}
方法2:
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter parser = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
java.time.LocalDateTime dt = java.time.LocalDateTime.parse(timestamp, parser);
ZonedDateTime zdt = ZonedDateTime.of(dt, java.time.ZoneId.of("UTC"));
return OffsetDateTime.from(zdt);
}
第一种方法不起作用,因为它抱怨以下内容:
java.time.format.DateTimeParseException:无法解析文本“2017-11-27T19:02:42”:无法从 TemporalAccessor:{} 获取 OffsetDateTime,ISO 解析为 2017-11-27T19:02:42 java.time.format.Parsed 类型的
据我了解,这是因为字符串没有 ZoneId。如何在格式化程序上覆盖 ZoneId 以便忽略它?
第二种方法来自 from this question 并且有效,但它需要 2 次额外的转换,我想避免这些额外的转换。
我们将不胜感激。
【问题讨论】:
-
您的预期结果是什么?由于字符串中没有时区或偏移量,因此您需要确定要使用的偏移量。
标签: java datetime timezone-offset zoneddatetime