Skip to content Skip to sidebar Skip to footer

How Do I Convert Epoch Time To Date And Time Zone Is Defined In Offset In Millisecond

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

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

Table of which java.time library to use with which version of Java or Android.

Post a Comment for "How Do I Convert Epoch Time To Date And Time Zone Is Defined In Offset In Millisecond"