【问题标题】:Wrong time.Duration calculated时间错误。计算的持续时间
【发布时间】:2021-12-29 22:19:58
【问题描述】:

我有一个返回“正常运行时间”值的 HTTP 服务器。简短版代码:

package main

import (
    "fmt"
    "net/http"
    "time"
)

var startup time.Time

func main() {
    startup = time.Now()
    http.HandleFunc("/", RootHandler)
    http.ListenAndServe(":39000", nil)
}

func RootHandler(w http.ResponseWriter, r *http.Request) {
    now := time.Now()
    fmt.Fprintf(w, "startup: %s\nnow: %s\nuptime (.Since): %s\nuptime (.Sub): %s",
        startup.Format("2006-01-02 15:04:05"),
        now.Format("2006-01-02 15:04:05"),
        time.Since(startup).Round(time.Second),
        now.Sub(startup).Round(time.Second),
    )
}

我在 22:10:33 启动了服务器,大约 1 小时 10 分后我让我的电脑进入睡眠状态。早上,电脑醒来后,我得到了下一个回复:

startup: 2021-11-18 22:10:33
now: 2021-11-19 05:35:20
uptime (.Since): 1h13m14s
uptime (.Sub): 1h13m14s

我正在使用 Windows,但代码是从 WSL v2 执行的。谁能解释为什么时间计算错误?

附:如果我直接从 Windows 运行 - 响应很好(时间差计算正确)。

【问题讨论】:

    标签: go time windows-subsystem-for-linux


    【解决方案1】:

    您的代码看起来不错。据我了解,WSL v2 是它自己的环境。在这种情况下,它从那里获得时间。我会检查系统上的时间。

    https://tomssl.com/fixing-clock-drift-in-wsl2-using-windows-terminal/

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 2022-08-06
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多