问题描述
我有一个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
对象上有一个不错的构造函数,该函数采用所有三种格式作为Strings并将其转换。 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!