Q1. How do I create a golang time struct from a nanosecond timestamp?
Q2. How do I then compute the number of hours since this timestamp?
Q1. How do I create a golang time struct from a nanosecond timestamp?
Q2. How do I then compute the number of hours since this timestamp?
In Go a "time" object is represented by a value of the struct type time.Time
.
You can create a Time
from a nanosecond timestamp using the time.Unix(sec int64, nsec int64)
function where it is valid to pass nsec
outside the range [0, 999999999]
.
And you can use the time.Since(t Time)
function which returns the elapsed time since the specified time as a time.Duration
(which is basically the time difference in nanoseconds).
t := time.Unix(0, yourTimestamp)
elapsed := time.Since(t)
To get the elapsed time in hours, simply use the Duration.Hours()
method which returns the duration in hours as a floating point number:
fmt.Printf("Elapsed time: %.2f hours", elapsed.Hours())
Try it on the Go Playground.
Note:
Duration
can format itself intelligently in a format like "72h3m0.5s"
, implemented in its String()
method:
fmt.Printf("Elapsed time: %s", elapsed)
2262-04-11 23:47:16.854775807 +0000 UTC
Feb 9, 2017 at 21:01
You pass the nanoseconds to time.Unix(0, ts)
, example:
func main() {
now := time.Now()
ts := int64(1257856852039812612)
timeFromTS := time.Unix(0, ts)
diff := now.Sub(timeFromTS)
fmt.Printf("now: %v\ntime from ts: %v\ndiff: %v\ndiff int:", now, timeFromTS, diff, int64(diff))
}