java - 在Windows机器上获取手动设置的时区

标签 java java-8

我希望能够获取我的机器设置的任何时区,而无需在代码中手动指定时区。我可能不在那个时区,但目标是使用计算机设置的时区。

我的时区区域是 America/New_York,使用 ZoneId.systemDefault() (EDT)。但是,我已将计算机的时区设置为太平洋时间 (PDT)。我已经尝试过下面指定的代码。在 Java 8 中实现这一目标的最佳方法是什么?

LocalDateTime currentDateTime = LocalDateTime.of(date.getYear(), date.getMonth(), date.getDay(), hour, minute, 0);
        ZonedDateTime zonedDateTime = currentDateTime.atZone(ZoneId.systemDefault());
        date = Date.from(zonedDateTime.toInstant());

我希望时区为 Amrica/Dawson 或 America/Tijuana (UTC -08:00),但我得到的是 America/New_York (UTC -05:00)

最佳答案

这是我为得到答案而编写的完整代码:

TimeZone.setDefault(null);
System.setProperty("user.timezone", "");
//(above) force fetches and sets the JVM to the timezone the system is set to
LocalDateTime currentDateTime = LocalDateTime.of(date.getYear(), date.getMonth(), date.getDay(), hour, minute, 0);
ZonedDateTime zonedDateTime = currentDateTime.atZone(ZoneId.systemDefault());
date = Date.from(zonedDateTime.toInstant());

问题是我可能已经更改了@Matt 提到的系统时区。然而,我发现尽管手动更改时区,JVM 时间并没有改变。

TimeZone.setDefault(null);
System.setProperty("user.timezone", "");

(上图)允许我清除之前设置的 JVM 时区。

编辑2019年4月26日

我更新了逻辑以支持太平洋时间的夏令时。我遇到了一个问题,我的时间设置为 PST 而不是 PDT,因此我没有使用上述逻辑,而是将其更改为获取区域 ID 并将其与 Calendar 类一起使用。下面是完整的逻辑:

TimeZone.setDefault(null);
System.clearProperty​("user.timezone"); //04/26/2019 EDIT This was suggested as a cleaner way of clearing the user timezone in the system.
//(above) force fetches and sets the JVM to the timezone the system is set to
System.out.println("Zone: "+ZoneId.systemDefault()+" isDaylightsavings? "+ZoneId.systemDefault().getRules().isDaylightSavings(Instant.now())+" currentDateTime: "+currentDateTime);
String timeZone = ""+ZoneId.systemDefault();
Calendar selectedDate = Calendar.getInstance(TimeZone.getTimeZone(timeZone)); // important when it comes to determining PDT or PST
date = selectedDate.getTime();

关于java - 在Windows机器上获取手动设置的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55835224/

相关文章:

java - 验证字符串是否精确为 "kind"(java)

Java bean 验证带范围的大写字母

java - ZonedDateTime更改行为jdk 8/11

mysql - 将 java.time 作为 tinyblob 持久化到 Date

java - 用于保存并随后组合稀疏数据的数据结构

java - 在 Docker 中使用 Spring Boot Actuator?

java - 如何扩展Spring MVC Controller 注解?

java - Jersey 客户端单例与多个 Jersey 客户端实例

java - 手动连接mySQL到eclipse/Spring Boot

java8 简化映射转换