首页 > 解决方案 > Api 将日期时间作为数字返回,我怎样才能使它成为正确的日期?

问题描述

我正在使用一个外部 api(使用 MongoDB),它向我发送这样的日期格式:

"documentDate": 1574283600000,

我认为它的日期为:

"documentDate" : ISODate("2019-02-28T00:00:00.000+03:00"),

但它返回我的数字。我怎样才能使它成为这样一个合适的日期:

03/12/2019

标签: javajsonmongodbspring-boot

解决方案


我会使用java.time该值看起来像(并且很可能是)一个时刻,计为epoch milliseconds。您可以将其转换为一个Instant,然后进一步将其转换为一个知道偏移量或时区的日期时间对象。

看看这个:

public static void main(String[] args) {
    // your sample millis
    long documentDateInMillis = 1574283600000L;
    // parse it to a moment in time: an Instant
    Instant instant = Instant.ofEpochMilli(documentDateInMillis);
    // then create an offset aware datetime object by adding an actual offset
    OffsetDateTime odt = OffsetDateTime.ofInstant(instant, ZoneOffset.of("+03:00"));
    // print it in the default representation
    System.out.println("Default formatting:\t" + odt);
    // or in an ISO representation of the date only
    System.out.println("ISO local date:\t\t"
                        + odt.format(DateTimeFormatter.ISO_LOCAL_DATE));
    // or in a custom representation (date only, too)
    System.out.println("Custom formatting:\t"
                        + odt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
}

输出如下:

Default formatting: 2019-11-21T00:00+03:00
ISO local date:     2019-11-21
Custom formatting:  21/11/2019

推荐阅读