I have an HTTP server that returns the "uptime" value. The short version of the code:
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),
)
}
I started the server at 22:10:33 and after about 1h10m I put my computer to sleep. In the morning, after the computer awake, I got the next response:
startup: 2021-11-18 22:10:33
now: 2021-11-19 05:35:20
uptime (.Since): 1h13m14s
uptime (.Sub): 1h13m14s
I'm working on windows, but the code was executed from WSL v2. Can someone explain why is time calculated wrong?
PS If I'm running directly from windows - the response is fine (time difference calculated correctly).
Your code seems fine. From my understanding WSL v2 is it's own environment. In which case, it's getting the time from there. I would check the time on the system.
https://tomssl.com/fixing-clock-drift-in-wsl2-using-windows-terminal/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.