Mali
Mali

Reputation: 61

Api returns date-time as numbers how can I make it a proper date?

I am using an external api(Uses MongoDB) which sends me a date format like this:

"documentDate": 1574283600000,

I think it holds date as:

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

But it returns me numbers. How can I make it a proper date like this:

03/12/2019

Upvotes: 1

Views: 1231

Answers (1)

deHaar
deHaar

Reputation: 18578

I would use java.time as the value looks like (and most likely is) a moment in time counted as epoch milliseconds. You can convert it to an Instant and then further convert it to a datetime object aware of an offset or a time zone.

Have a look at this:

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

The output is the following:

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

Upvotes: 1

Related Questions