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();
添加回答
舉報