
Truncating a Unix timestamp to the hour using Go
6 Jan 2021 #pattern #golang #development
If you want to truncate a unix timestamp to the hour value, you can do this using the Truncate
function:
import ( "time") // UnixTruncateToHour returns the timestamp truncated to the hour.func UnixTruncateToHour(unixTime int64) int64 { t := time.Unix(unixTime, 0).UTC() return t.Truncate(time.Hour).UTC().Unix()}
Truncate
returns the result of roundingt
down to a multiple ofd
(since the zero time). Ifd <= 0
,Truncate
returnst
stripped of any monotonic clock reading but otherwise unchanged.
Truncate
operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus,Truncate(Hour)
may return a time with a non-zero minute, depending on the time's Location.
Be aware that there is also a Round
function:
import ( "time") // UnixRoundToHour returns the timestamp rounded to the hour.func UnixRoundToHour(unixTime int64) int64 { t := time.Unix(unixTime, 0).UTC() return t.Round(time.Hour).UTC().Unix()}
Round
returns the result of roundingt
to the nearest multiple ofd
(since the zero time). The rounding behavior for halfway values is to round up. Ifd <= 0
,Round
returnst
stripped of any monotonic clock reading but otherwise unchanged.
Round
operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus,Round(Hour)
may return a time with a non-zero minute, depending on the time's Location.