get system uptime in go

To get the system uptime in Go, we can use the time.Since() function to get the duration since the system started, like this:

main.go
package main

import (
    "fmt"
    "time"
)

func main() {
    uptime := time.Since(time.Now().Add(-time.Duration(time.Since(time.Now().Add(0))).Truncate(time.Second)))
    fmt.Println("System uptime:", uptime)
}
215 chars
12 lines

This code gets the current time, subtracts the duration since the current time (which should be 0), and then truncates to the nearest second to get the time since the system started. The result is a time.Duration value which can be formatted and printed as desired.

related categories

gistlibby LogSnag