Java 8 ZoneOffset - 如何获取当前系统 UTC 偏移量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42468753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 ZoneOffset - How to get current system UTC offset
提问by Allison Burgers
I want to get current ZoneOffsetof my system.
I tried to do that but I couldn't find a way.
Also, I was looking for a solution but I didn't find any.
Is it possible to do that in Java?
我想获得我系统的当前ZoneOffset。
我试图这样做,但我找不到办法。
另外,我一直在寻找解决方案,但没有找到。
可以在 Java 中做到这一点吗?
EDIT:
My question is different to this. I would like to know the current system UTC, not how to convert between TimeZone offset representation or TimeZone storing.
编辑:
我的问题与此不同。我想知道当前系统的 UTC,而不是如何在 TimeZone 偏移表示或 TimeZone 存储之间进行转换。
回答by JodaStephen
Your request has two parts:
您的请求有两个部分:
- the offset of "my system" - thus you need the system time-zone -
ZoneId.systemDefault()
- the "current" offset - thus you need the current instant -
Instant.now()
- “我的系统”的偏移量 - 因此您需要系统时区 -
ZoneId.systemDefault()
- “当前”偏移量 - 因此您需要当前时刻 -
Instant.now()
These are tied together using ZoneRules
, to get the following:
这些使用ZoneRules
,捆绑在一起以获得以下内容:
ZoneOffset o = ZoneId.systemDefault().getRules().getOffset(Instant.now());
For simplicty, you might want to use OffsetDateTime
:
为简单起见,您可能需要使用OffsetDateTime
:
ZoneOffset o = OffsetDateTime.now().getOffset();
This works because OffsetDateTime.now()
uses both ZoneId.systemDefault()
and Instant.now()
internally.
这是有效的,因为同时OffsetDateTime.now()
使用ZoneId.systemDefault()
和Instant.now()
内部。
回答by Micha? Szewczyk
Yes, it's possible:
是的,这是可能的:
ZoneOffset.systemDefault().getRules().getOffset(Instant.now())
or you can replace Instant instance with LocalDateTime instance:
或者你可以用 LocalDateTime 实例替换 Instant 实例:
ZoneOffset.systemDefault().getRules().getOffset(LocalDateTime.now())