1 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是我為得到答案而編寫(xiě)的完整代碼:
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());
問(wèn)題是我可能已經(jīng)更改了@Matt 提到的系統(tǒng)時(shí)區(qū)。但是,我發(fā)現(xiàn)盡管手動(dòng)更改了時(shí)區(qū),但 JVM 時(shí)間并沒(méi)有改變。
TimeZone.setDefault(null);
System.setProperty("user.timezone", "");
(上)允許我清除之前設(shè)置的 JVM 時(shí)區(qū)。
編輯 04/26/2019
我更新了我的邏輯以支持太平洋時(shí)間的夏令時(shí)。我遇到了一個(gè)問(wèn)題,我的時(shí)間是設(shè)置 PST 而不是 PDT,所以我沒(méi)有使用上述邏輯,而是將其更改為獲取區(qū)域 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();
添加回答
舉報(bào)