问题描述
我正在尝试更改标准格式 2014-09-11T21:28:29.429209Z
进入一个不错的MMM d yyyy hh:mm z格式,但是我当前的代码失败了。
I am trying to change from standard ISO 8601 format 2014-09-11T21:28:29.429209Z
into a nice MMM d yyyy hh:mm z format, however my current code is failing.
public void setCreatedAt( String dateTime ) {
LocalDate newDateTime = LocalDate.parse(dateTime);
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a z");
createdAt = newDateTime.format(format);
}
catch (Exception e) {
}
}
我收到来自api的时间和日期。
I am receiving the time and date from an api.
推荐答案
A java.time.LocalDate
是ISO-8601日历系统中没有时区的日期,例如2007-12-03,因此那里没有足够的信息。请改用 java.time.ZonedDateTime
。
A java.time.LocalDate
is "a date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03" so there is not enough information there. Use java.time.ZonedDateTime
instead.
此外,吞下这样的例外情况会使故障排除更加困难。当您不打算处理异常时,要么根本不捕获它,捕获并重新抛出它包装在RuntimeException中或至少记录它( e.printStackTrace()
或类似的)。
Also, swallowing exceptions like that makes it much harder to troubleshoot. When you don't intend to handle an exception either don't catch it at all, catch and re-throw it wrapped in a RuntimeException or at the very least log it (e.printStackTrace()
or similar) .
这篇关于如何在Java中格式化ISO-8601的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!