如何使用java-8转换以utc秒为单位的时间和以秒为单位的时区偏移量? [英] How to convert time in utc second and timezone offset in second to date using java-8?

查看:318
本文介绍了如何使用java-8转换以utc秒为单位的时间和以秒为单位的时区偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以utc秒为单位的日期,其时区以sec为单位.我想使用java8 ZoneOffset类将其转换为格式为yyyy-mm-dd的日期字符串.以下是时间(以秒为单位)和偏移量

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

现在我想使用java-8 DateTime API以以下格式获取日期吗?

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

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

推荐答案

您可以使用即时以获取

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

然后从中获取 LocalDate

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

如果要以字符串格式输出,请使用 DateTimeFormatter

If you want string formatted output use DateTimeFormatter

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

这篇关于如何使用java-8转换以utc秒为单位的时间和以秒为单位的时区偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆