Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何获取时区的当前时间_Java - Fatal编程技术网

Java 如何获取时区的当前时间

Java 如何获取时区的当前时间,java,Java,我将特定操作的UTC时间偏移存储如下:(这一个用于UTC+2) 如何使用Java中的双时间偏移量获取该时区的当前时间?您可以组合使用 从小时偏移量获取偏移区域的步骤 从当前即时和区域偏移量 首先,您需要将double值转换为ZoneOffset: double utc=2.0; 区域偏移量=总秒的区域偏移量((int)(utc*3600)); 然后可以获取当前时间: OffsetDateTime now=Instant.now().atOffset(offset); 样本输出 2020

我将特定操作的UTC时间偏移存储如下:(这一个用于UTC+2)

如何使用Java中的双时间偏移量获取该时区的当前时间?

您可以组合使用

  • 从小时偏移量获取偏移区域的步骤
  • 从当前
    即时
    区域偏移量


首先,您需要将
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.5Ehhh。。。。否,强制转换为
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