Java 如何获取时区的当前时间
我将特定操作的UTC时间偏移存储如下:(这一个用于UTC+2) 如何使用Java中的双时间偏移量获取该时区的当前时间?您可以组合使用Java 如何获取时区的当前时间,java,Java,我将特定操作的UTC时间偏移存储如下:(这一个用于UTC+2) 如何使用Java中的双时间偏移量获取该时区的当前时间?您可以组合使用 从小时偏移量获取偏移区域的步骤 从当前即时和区域偏移量 首先,您需要将double值转换为ZoneOffset: double utc=2.0; 区域偏移量=总秒的区域偏移量((int)(utc*3600)); 然后可以获取当前时间: OffsetDateTime now=Instant.now().atOffset(offset); 样本输出 2020
- 从小时偏移量获取偏移区域的步骤
- 从当前
即时
和
区域偏移量
首先,您需要将
double
值转换为ZoneOffset
:
double utc=2.0;
区域偏移量=总秒的区域偏移量((int)(utc*3600));
然后可以获取当前时间:
OffsetDateTime now=Instant.now().atOffset(offset);
样本输出
2020-09-22T21:16:42.816236600+02:00
另外两种选择:
使用:
double utc = 2.0;
备选案文1:
ZonedDateTime nowAlt1 = Instant.now().atZone(ZoneOffset.ofTotalSeconds((int) utc * 3600));
备选案文2:
ZonedDateTime nowAlt2 = ZonedDateTime.ofInstant(Instant.now(), ZoneOffset.ofTotalSeconds((int) utc * 3600));
备选案文1和2:
public static void main(String[] args) {
double utc = 2.0;
ZonedDateTime nowAlt1 = Instant.now().atZone(ZoneOffset.ofTotalSeconds((int) utc * 3600));
ZonedDateTime nowAlt2 = ZonedDateTime.ofInstant(Instant.now(), ZoneOffset.ofTotalSeconds((int) utc * 3600));
System.out.println("nowAlt1: " + nowAlt1);
System.out.println("nowAlt2: " + nowAlt2);
}
输出:
nowAlt1: 2020-09-22T23:15:00.254912800+02:00
nowAlt2: 2020-09-22T23:15:00.253915600+02:00
在这里阅读更多关于java.time的信息,可以让您了解何时使用不同类型的java.time:
最好使用
Instant.now().atOffset(…)
。减少浪费。更清晰的意图。虽然答案足够有用,不会被否决,但它实际上并没有回答问题,即“如何使用Java中的这个double
time offset获得该时区的当前时间?”@Andreas从double转换为int?因为小时的分区偏移量(2)似乎比总秒的分区偏移量(3600*2)双印度=5.5代码>Ehhh。。。。否,强制转换为int
将不起作用。或者double offset=1.325556代码>,又名1:19:32
,由欧洲/阿姆斯特丹使用
1916-1937年?
public static void main(String[] args) {
double utc = 2.0;
ZonedDateTime nowAlt1 = Instant.now().atZone(ZoneOffset.ofTotalSeconds((int) utc * 3600));
ZonedDateTime nowAlt2 = ZonedDateTime.ofInstant(Instant.now(), ZoneOffset.ofTotalSeconds((int) utc * 3600));
System.out.println("nowAlt1: " + nowAlt1);
System.out.println("nowAlt2: " + nowAlt2);
}
nowAlt1: 2020-09-22T23:15:00.254912800+02:00
nowAlt2: 2020-09-22T23:15:00.253915600+02:00