#development #golang #pattern

If you want to truncate a unix timestamp to the hour value, you can do this using the Truncate function:

1import (
2    "time"
3)
4
5// UnixTruncateToHour returns the timestamp truncated to the hour.
6func UnixTruncateToHour(unixTime int64) int64 {
7    t := time.Unix(unixTime, 0).UTC()
8    return t.Truncate(time.Hour).UTC().Unix()
9}

Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t 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:

1import (
2    "time"
3)
4
5// UnixRoundToHour returns the timestamp rounded to the hour.
6func UnixRoundToHour(unixTime int64) int64 {
7    t := time.Unix(unixTime, 0).UTC()
8    return t.Round(time.Hour).UTC().Unix()
9}

Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t 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.