使用 Java 8 转换像 Joda DateTime(String) 这样的日期时间字符串 [英] Convert date time string like Joda DateTime(String) with Java 8
问题描述
我有一个 API,它可以以三种可能的格式返回 JSON 中的日期值:
I have an API that can return date values in JSON in three possible formats:
- 2017-04-30T00:00+02:00
- 2016-12-05T04:00
- 2016-12-05
我需要将所有三个转换为 java.time.LocalTimeDate
.Joda 在 DateTime
对象上有一个很好的构造函数,它接受所有三种格式作为字符串并转换它们.DateTime dt = new DateTime(StringFromAPI);
就够了.
I need to convert all three into a java.time.LocalTimeDate
. Joda has a nice constructor on the DateTime
object which takes in all three formats as Strings and converts them. DateTime dt = new DateTime(StringFromAPI);
is enough.
Java 8(java.time
包)中是否有类似的功能?看来我现在首先必须对 String
进行正则表达式来检查格式,然后创建一个 LocalDateTime
、ZonedDateTime
或 LocalDate
并将后者 2. 转换为 LocalDateTime
.对我来说似乎有点麻烦.有没有简单的方法?
Is there a similar capability in Java 8 (java.time
package)? It seems I now first have to regex the String
to check the format, then create either a LocalDateTime
, ZonedDateTime
or LocalDate
and convert the latter 2. to LocalDateTime
. Seems a bit cumbersome to me. Is there a easy way?
推荐答案
我提出了两个选项,每个选项都有其优缺点.
I am presenting two options, each with its pros and cons.
一,构建自定义DateTimeFormatter
以接受您的三种可能的格式:
One, build a custom DateTimeFormatter
to accept your three possible formats:
public static LocalDateTime parse(String dateFromJson) {
DateTimeFormatter format = new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.optionalStart()
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.optionalStart()
.appendOffsetId()
.optionalEnd()
.optionalEnd()
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter();
return LocalDateTime.parse(dateFromJson, format);
}
一方面,它很干净,另一方面,有人很容易发现它有点棘手.对于您问题中的三个示例字符串,它会生成:
On one hand, it’s clean, on the other, someone could easily find it a bit tricky. For the three sample strings in your question it produces:
2017-04-30T00:00
2016-12-05T04:00
2016-12-05T00:00
另一种选择,依次尝试三种不同的格式,然后选择一种有效的格式:
The other option, try the three different formats in turn and pick the one that works:
public static LocalDateTime parse(String dateFromJson) {
try {
return LocalDateTime.parse(dateFromJson);
} catch (DateTimeParseException e) {
// ignore, try next format
}
try {
return LocalDateTime.parse(dateFromJson, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
} catch (DateTimeParseException e) {
// ignore, try next format
}
return LocalDate.parse(dateFromJson).atStartOfDay();
}
我不认为这是最漂亮的代码,还是有人认为它比第一个选项更直接?我认为仅依赖内置的 ISO 格式是有好处的.三个示例字符串的结果与上述相同.
I don’t consider this the most beautiful code, still some may think it’s more straightforward than the first option? I think there’s a quality in relying on the built-in ISO formats alone. The results for your three sample strings are the same as above.
这篇关于使用 Java 8 转换像 Joda DateTime(String) 这样的日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!