Search code examples
javaepochmillisecondszoneddatetimedate

convert millis to ZonedDateTime not working


I have this millis in long:

1570046362841

when converting with version 1:

var myDate = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1570046362841), ZoneId.of("America/New_York"));

I will get this result (which is wrong!):

+51722-10-16T03:58:54-04:00[America/New_York]

However, when converting with version 2:

 final String dateFormat = "yyyy-MM-dd HH:mm:ss SSS";
 SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
 formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
 var dateObj = new Date(1570046362841);
 var myDate = formatter.format(dateObj);

I get the correct result:

2019-10-02 15:59:59 934

Why is version 1 wrong? What is wrong in version 1?


Solution

  • Instead of Instant.ofEpochSecond() you need to use Instant.ofEpochMilli() because you have millis.