DateTimeFormatter不能应用于(java.util.Date)

huangapple go评论146阅读模式
英文:

DateTimeFormatter cannot be applied to (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中的format (java.time.temporal.TemporalAccessor)不能应用于(java.util.Date),并且返回了类似以下错误的信息:"java.incompatible.types:无法将java.util.Date转换为java.time.temporal.TemporalAccessor"

我正在为此进行后台研究,仍然在努力寻找最佳解决方法。我想知道您对此的想法,这将帮助我找到更好的解决方案。非常感谢您的建议。谢谢。

英文:

I have decided to use a DateTimeFormatter instead of using SimpleDateFormat because I heard SimpleDateFormat is not thread-safe. I have declared DateTimeFormatter inside Constant file as follows.

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

and inside my class file my implementation like this.

String value = Constant.GENERAL_TZ_FORMATTER.format(new Date(date.get()));

but seems like this is not correct implementation. Because it says format (java.time.temporal.TemporalAccessor) in DateTimeFormatter cannot be applied to (java.util.Date) and returns some error like this, "java.incompatible.types: java.util.Date cannot be converted to java.time.temporal.TemporalAccessor"

I'm doing background research for this and still struggling to find the best way to resolve it. I like to know your ideas about this and it will help me to find a better solution. Really appreciate your suggestions. Thank you.

答案1

得分: 4

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);
       // 或者: dateTime.format(GENERAL_TZ_FORMATTER)
System.out.println(value);

由于我处于美国东部时区,我得到的输出是:

2020-08-25 02:22:23 EDT

作为单个语句,您可以将其写成以下形式,但您可能会将其格式化为多行,以便更容易阅读。

// 单行
String value = Instant.ofEpochMilli(epochMilli).atZone(ZoneId.systemDefault()).format(GENERAL_TZ_FORMATTER);
// 为了可读性进行格式化
String value = Instant.ofEpochMilli(epochMilli)
                      .atZone(ZoneId.systemDefault())
                      .format(GENERAL_TZ_FORMATTER);
英文:

new Date(date.get()) would mean that date.get() returns a long with the milliseconds-since-epoch.

Since you're using DateTimeFormatter from the new Java Time API, you must give it a date object from that same API. Instant is such an object that can be created with a milliseconds-since-epoch value.

However, the format string you're using cannot be used with an Instant, so you first need to convert it to a ZonedDateTime, in the relevant time zone. In the code below, we'll assume you want the default time zone of the JVM, which is what the old java.util.Date API would have used.

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);

Since I'm in the US Eastern time zone, I get:

2020-08-25 02:22:23 EDT

As a single statement, you can write it as follows, but you'd probably format it over multiple lines to make it easier to read.

// 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);

答案2

得分: 1

DateTimeFormatter是Java新时间API的一部分。如果您想要使用DateTimeFormatter,则应该考虑使用LocalDateTime而不是java.util.Date

您可以像下面这样在您的情况中利用DateTimeFormatter

String value = Constant.GENERAL_TZ_FORMATTER.format(LocalDateTime.now());
英文:

DateTimeFormatter is a part of java new time API. If you want to use DateTimeFormatter than you should consider using LocalDateTime instead of java.util.Date

You can utilize the DateTimeFormator in your case like below:

String value = Constant.GENERAL_TZ_FORMATTER.format(LocalDateTime.now());

答案3

得分: 0

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);
    }
}

You can use SimpleDateFormat as mentioned above.

More about SimpleDateFormat, you will get an idea by following link.


<details>
<summary>英文:</summary>

    class Constant {
        public static final SimpleDateFormat GENERAL_TZ_FORMATTER = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss z&quot;);
    
        public static void main(String[] args) {
            String value = Constant.GENERAL_TZ_FORMATTER.format(new Date());
            System.out.println(value);
        }
    }

You can use, **`SimpleDateFormat`**  as mentioned above.

More about SimpleDateFormat ,you will get an idea by following [**`link`**][1]


  [1]: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

</details>



huangapple
  • 本文由 发表于 2020年8月25日 13:02:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63572330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定