亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Windows 機器上獲取手動設置時區

在 Windows 機器上獲取手動設置時區

呼喚遠方 2022-10-20 15:19:15
我希望能夠獲取我的機器設置的任何時區,而無需在代碼中手動指定時區。我可能不在那個時區,但目標是使用計算機設置的時區。在位置上,我的時區區域是 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)
查看完整描述

1 回答

?
GCT1015

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();


查看完整回答
反對 回復 2022-10-20
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號