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

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


在位置上,我的时区区域是 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)


呼唤远方
浏览 256回答 1
1回答

GCT1015

这是我为得到答案而编写的完整代码:TimeZone.setDefault(null);System.setProperty("user.timezone", "");//(above) force fetches and sets the JVM to the timezone the system is set toLocalDateTime 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 时区。编辑 04/26/2019我更新了我的逻辑以支持太平洋时间的夏令时。我遇到了一个问题,我的时间是设置 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 toSystem.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 PSTdate = selectedDate.getTime();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java