WSL2 Ubuntu 時間使用錯誤的 TZ 來計算位置時間?

WSL2 Ubuntu 時間使用錯誤的 TZ 來計算位置時間?

我有一台在 Windows 10 中運行的 Ubuntu 18.04 WSL2 機器,有時我會遇到這個奇怪的問題,即 WSL2 機器中的時間不同步。我的時區是東部時間 (-5),正如您在下面看到的,我的 WSL 是未來 5 小時。感覺由於某種原因,我的 WSL 機器將我的當地時間解釋為 UTC,並根據該資訊進行計算。

WSL2

$ date 
Fri Jan 22 03:13:28 EST 2021
$ cat /etc/timezone
America/Toronto
$ date +"%Z %z"
EST -0500

電源外殼

> date
Thursday, January 21, 2021 10:13:31 PM
> Get-TimeZone


Id                         : Eastern Standard Time
DisplayName                : (UTC-05:00) Est (É.-U. et Canada)
StandardName               : Est
DaylightName               : Est (heure d’été)
BaseUtcOffset              : -05:00:00
SupportsDaylightSavingTime : True

我嘗試做一個sudo dpkg-reconfigure tzdata但沒有幫助。

編輯:添加螢幕截圖,時間與我之前提到的時間不匹配,但螢幕截圖顯示了正確的本地時間和時區。

在此輸入影像描述

答案1

我有一台在 Windows 10 中運行的 Ubuntu 18.04 WSL2 機器,有時我會遇到這個奇怪的問題,即 WSL2 機器中的時間不同步。我的時區是東部時間 (-5),正如您在下面看到的,我的 WSL 是未來 5 小時。感覺由於某種原因,我的 WSL 機器將我的當地時間解釋為 UTC,並根據該資訊進行計算。

這是 WSL2 的已知問題:系統日期與 Windows 不同 (WSL 2) #4245

您必須在 WSL2 實例中執行以下命令:

sudo hwclock -s

您可以改為執行以下 PowerShell 命令:

wsl -u root sh -C "hwclock -S"

您還必須執行下列 PowerShell 命令:

wsl --shutdown

執行該命令後,您必須重新啟動 WSL 實例。

該解決方案還要求使用 Chrony 並在其中註解掉以下選項/etc/chrony/chrony.conf

# Stop bad estimates upsetting machine clock.
# maxupdateskew 100.0

如果您還沒有使用它:

sudo apt-get update && sudo apt-get install -y chrony && sudo chronyd

另一種解決方案是將以下內容新增至 .bashrc 中:

# WSL2 clock skew hack
__customprompt() {
  NOW=$(date +%s)
  if (( NOW > WSL_NEXT_CLOCKSYNC )); then
    echo "$(date -Iseconds) - hwclock [$WSL_NEXT_CLOCKSYNC : $NOW]" >> ~/.wsltimesync
    nohup wsl.exe -u root -c 'hwclock -s' &>/dev/null &
    export WSL_NEXT_CLOCKSYNC=$(date --date='+5 minutes' +%s)
  fi
}

來源:

另一種替代解決方案是根據記錄的特定事件的偵測在 Windows 中自動處理它。

這可以透過以下 PowerShell 腳本來處理:

function Log($message) {
    $output = (Get-Date).ToUniversalTime().ToString("u") + "`t$message"
    Add-Content -Path "~/.wsl-clock.log" -Value $output
}

Log "********************************"
Log "*** Update WSL clock starting..."

$runningDistroCount = wsl --list --running --quiet |
        Where-Object {$_ -ne ""} |
        Measure-Object |
        Select-Object -ExpandProperty Count

if ($runningDistroCount -eq 0){
    Log "No Distros - quitting"
    exit 0
}

$originalDate=wsl sh -c "date -Iseconds"

Log "Performing reset..."
$result = wsl -u root sh -c "hwclock -s" 2>&1
$success = $?
if (-not $success){
    Log "reset failed:"
    Log $result
    exit 2
} else {
    $newDate=wsl bash -c "date -Iseconds"
    Log "clock reset"
    Log "OriginalDate:$originalDate"
    Log "NewDate:     $newDate"
    exit 0
}

來源:使用 WSL 2 修復時脈偏差

您也可以使用wsl時鐘

其他資源:

答案2

我剛剛發出了以下命令:

sudo hwclock -s

這對我有用。此命令按描述修復了問題這裡

我當時使用的環境是:

  • 作業系統:Windows 10
  • 運行 Ubuntu 22.04.2 LTS 的 WSL

相關內容