How Do I Convert Epoch Time To Date And Time Zone Is Defined In Offset In Millisecond
Solution 1:
java.time and ThreeTenABP
intoffsetSeconds= -14_400;
longsunriseSeconds=1_569_494_827L;
ZoneOffsetoffset= ZoneOffset.ofTotalSeconds(offsetSeconds);
InstantsunriseInstant= Instant.ofEpochSecond(sunriseSeconds);
OffsetDateTimesunriseDateTime= 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.
Avoid java.util.Date
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).
Question: Can I use java.time on Android below API level 26?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. In this case the conversion is:
Date.from(sunriseInstant)
(a bit simpler). - In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Post a Comment for "How Do I Convert Epoch Time To Date And Time Zone Is Defined In Offset In Millisecond"