How to convert epoch like 1413225446.92000
to ZonedDateTime
in java?
The code given expects long value hence this will throw NumberFormatException
for the value given above.
ZonedDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateInMillis)), ZoneId.of(TIME_ZONE_PST));
Split the number into a pair of 64-bit long integers:
Pass those numbers to the factory method
Instant.ofEpochSecond(long epochSecond, long nanoAdjustment)
With an
Instant
in hand, proceed to assign a time zone to get aZonedDateTime
.Basil Bourque’s answer is a good one. Taking out the nanoseconds from the fractional part into an integer for nanoseconds may entail a pitfall or two. I suggest:
This prints
We don’t need 64 bits for the nanoseconds, so I am just using an
int
.If one day your epoch time comes in scientific notation (1.41322544692E9), the above will not work.
Please substitute your desired time zone in the region/city format if it didn’t happen to be Asia/Manila, for example America/Vancouver, America/Los_Angeles or Pacific/Pitcairn. Avoid three letter abbreviations like PST, they are ambiguous and often not true time zones.