1

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
Mali
  • 49
  • 1
  • 1
  • 11
  • I hope your value examples are not to represent the very same date or instant... – deHaar Mar 23 '20 at 09:39
  • 2
    To me it looks like the api returns the time in milliseconds since 01.01.1970. There's math to convert stuff like that. – cegredev Mar 23 '20 at 09:42
  • @deHaar no they are not the same just an example – Mali Mar 23 '20 at 09:46
  • Thanks for answering, I didn't know this was millisecond format, I found an answer here : https://stackoverflow.com/questions/12504537/convert-millisecond-string-to-date-in-java/12504608 I – Mali Mar 23 '20 at 09:54

1 Answers1

1

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
deHaar
  • 17,687
  • 10
  • 38
  • 51