Search code examples
javadatejava-8unix-timestamptimezone-offset

How to convert time in utc second and timezone offset in second to date using java-8?


I have a date in utc second and its time zone offset in sec. I would like to convert it to date string in format yyyy-mm-dd using java8 ZoneOffset class. Below is the time in seconds and offset

long time = 1574962442,
long offset = 3600

Now i want to obtain date in below format using java-8 DateTime API ?

 String date = 2019-11-28 // in yyyy-MM-dd

Solution

  • You can use Instant from java-8 DateTime API to obtains an OffsetDateTime of Instant from epoch seconds with offset seconds

    OffsetDateTime offsetDateTime = Instant.ofEpochSecond(time)
                                    .atOffset(ZoneOffset.ofTotalSeconds(offset));
    

    And the get LocalDate from it

    LocalDate localdate = offsetDateTime.toLocalDate();  //2019-11-28
    

    If you want string formatted output use DateTimeFormatter

    String output = localdate.format(DateTimeFormatter.ISO_LOCAL_DATE);