DateTimeFormatter无法应用于java.util.Date

问题描述

我已决定使用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”的错误

我正在为此做背景研究,但仍在努力寻找解决问题的最佳方法。我想知道您对此的想法,它将帮助我找到更好的解决方案。非常感谢您的建议。谢谢。

解决方法

new Date(date.get())表示date.get()返回带有毫秒数的long

由于您正在使用新的Java Time API中的DateTimeFormatter,因此必须为该API提供相同日期和时间的对象。 Instant就是这样一个对象,它可以使用毫秒级的自纪元值创建。

但是,您使用的格式字符串不能与Instant一起使用,因此您首先需要在相关时区将其转换为ZonedDateTime。在下面的代码中,我们假设您需要JVM的默认时区,这是旧的java.util.Date API会使用的默认时区。

long epochMilli = 1598336543358L;

DateTimeFormatter GENERAL_TZ_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

Instant instant = Instant.ofEpochMilli(epochMilli);
ZonedDateTime dateTime = instant.atZone(ZoneId.systemDefault());
String value = GENERAL_TZ_FORMATTER.format(dateTime);
       // or:  dateTime.format(GENERAL_TZ_FORMATTER)
System.out.println(value);

由于我处于美国东部时区,因此我得到:

2020-08-25 02:22:23 EDT

您可以将其编写为单个语句,如下所示,但是您可能需要将其格式化为多行以使其易于阅读。

// Single line
String value = Instant.ofEpochMilli(epochMilli).atZone(ZoneId.systemDefault()).format(GENERAL_TZ_FORMATTER);
// Formatted for readability
String value = Instant.ofEpochMilli(epochMilli)
                      .atZone(ZoneId.systemDefault())
                      .format(GENERAL_TZ_FORMATTER);
,

public void onSubmitClick() { quotesModel.setCompanyName(companyName.getValue()); quotesModel.setRecordNum(recordNum.getValue()); sendQuote(); } 是Java新时间API的一部分。如果您想使用DateTimeFormatter,则应该考虑使用DateTimeFormatter而不是LocalDateTime

您可以在以下情况下使用java.util.Date

DateTimeFormator
,
class Constant {
    public static final SimpleDateFormat GENERAL_TZ_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");

    public static void main(String[] args) {
        String value = Constant.GENERAL_TZ_FORMATTER.format(new Date());
        System.out.println(value);
    }
}

您可以如上所述使用 SimpleDateFormat

有关SimpleDateFormat的更多信息,您将通过关注link

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...