【发布时间】:2020-08-25 05:02:25
【问题描述】:
我决定使用 DateTimeFormatter 而不是 SimpleDateFormat,因为我听说 SimpleDateFormat 不是线程安全的。我在常量文件中声明了 DateTimeFormatter,如下所示。
public static final DateTimeFormatter GENERAL_TZ_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
在我的类文件中,我的实现是这样的。
String value = Constant.GENERAL_TZ_FORMATTER.format(new Date(date.get()));
但似乎这不是正确的实现。因为它说 DateTimeFormatter 中的格式 (java.time.temporal.TemporalAccessor) 不能应用于 (java.util.Date) 并返回类似这样的错误,“java.incompatible.types: java.util.Date cannot be converted to java.time.temporal.TemporalAccessor”
我正在为此进行背景调查,但仍在努力寻找解决问题的最佳方法。我想知道您对此的想法,它将帮助我找到更好的解决方案。非常感谢您的建议。谢谢。
【问题讨论】:
-
DateTimeFormatter是 java new time API 的一部分。如果您想使用DateTimeFormatter,则应考虑使用LocalDateTime而不是java.util.Date -
类似
String value = Constant.GENERAL_TZ_FORMATTER.format(LocalDateTime.now());
标签: java exception datetime-format simpledateformat