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?
The Now() function in Go language is used to find the current local time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Return Value: It returns the current local time.
Duration has a base type int64. Duration represents the elapsed time between two instants as an int64 nanosecond count”. The maximum possible nanosecond representation is up to 290 years.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With