有没有办法在java 8中将ZoneId转换为ZoneOffset? [英] Is there any way to convert ZoneId to ZoneOffset in java 8?

查看:6163
本文介绍了有没有办法在java 8中将ZoneId转换为ZoneOffset?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个epoch秒和一个zoneId,方法1.它可以转换为LocalDateTime系统默认的zoneId,但我找不到方法将第二个转换为LocalDateTime by method2,因为没有 ZoneOffset.systemDefault 。我认为这是模糊的。

I have an epoch second and a zoneId,by method1.It can be convert to LocalDateTime with system default zoneId,but I don't find the way to convert epoch second to LocalDateTime by method2,because there is no ZoneOffset.systemDefault.I think it's obscure.

import java.time.{Instant, LocalDateTime, ZoneId, ZoneOffset}

val epochSecond = System.currentTimeMillis() / 1000

LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), ZoneId.systemDefault())//method1
LocalDateTime.ofEpochSecond(epochSecond, 0, ZoneOffset.MAX)//method2


推荐答案

以下是如何从 ZoneId 获取 ZoneOffset

Instant instant = Instant.now(); //can be LocalDateTime
ZoneId systemZone = ZoneId.systemDefault(); // my timezone
ZoneOffset currentOffsetForMyZone = systemZone.getRules().getOffset(instant);

NB: ZoneId 可以有不同的偏移量在时间点和特定地方的历史。因此,选择不同的Instants将导致不同的偏移。

NB: ZoneId can have different offset depending on point in time and the history of the particular place. So choosing different Instants would result in different offsets.

这篇关于有没有办法在java 8中将ZoneId转换为ZoneOffset?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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