1 回答
TA贡献1827条经验 获得超4个赞
这是我为得到答案而编写的完整代码:
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 时区。
编辑 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 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();
添加回答
举报