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

让人想犯罪 __ 提交于 2021-02-08 12:15:38

问题


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

回答1:


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);



回答2:


you can use java 8 LocalDateTime APIs to achieve this.

LocalDateTime dateTime = LocalDateTime.ofEpochSecond(1574962442, 0, ZoneOffset.ofTotalSeconds(3600));

// for format
String formatted = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))


来源:https://stackoverflow.com/questions/59349957/how-to-convert-time-in-utc-second-and-timezone-offset-in-second-to-date-using-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!