I am parsing one api date related to the weather app.
Here I am getting time in epoch time I want to convert into Date time format.
I am getting sunrise time that is epoch time. It is 1569494827(input Time). I want to convert this time into a date. It has offset time in milliseconds -14400(offset in millisecond).
This time is New York Morning time. Its Output will be 06:47 AM but I am unable to convert this epoch time to Output time
This is a response: I have to convert into Date
"city": {
"id": 5128581,
"name": "New York",
"coord": {
"lat": 40.7306,
"lon": -73.9867
},
"country": "US",
"population": 8175133,
"timezone": -14400,
"sunrise": 1569494827,
"sunset": 1569538053
}
int offsetSeconds = -14_400;
long sunriseSeconds = 1_569_494_827L;
ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetSeconds);
Instant sunriseInstant = Instant.ofEpochSecond(sunriseSeconds);
OffsetDateTime sunriseDateTime = sunriseInstant.atOffset(offset);
System.out.println("Sunrise: " + sunriseDateTime);
Output is:
Sunrise: 2019-09-26T06:47:07-04:00
It may be needless to say that sunset goes in the same fashion.
If by i have to convert into Date you meant java.util.Date
: don’t. That class is poorly designed and long outdated and also cannot hold an offset. You’re much better off using java.time. Only if you need a Date
for a legacy API not yet upgraded to java.time, you need to convert. In this case you can ignore the offset (“timezone”) completely since the Date
cannot take it into account anyway. Just convert the Instant
that we got:
Date oldfashionedDate = DateTimeUtils.toDate(sunriseInstant);
System.out.println("As old-fashioned Date object: " + oldfashionedDate);
As old-fashioned Date object: Thu Sep 26 12:47:07 CEST 2019
A Date
always prints in the default time zone of the JVM, in my case Central European Summer Time (CEST), which is why we don’t get 6:47 in the morning (it’s a quite annoying and confusing behaviour).
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
Date.from(sunriseInstant)
(a bit simpler).org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).