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()
}
Truncatereturns the result of roundingtdown to a multiple ofd(since the zero time). Ifd <= 0,Truncatereturnststripped of any monotonic clock reading but otherwise unchanged.
Truncateoperates 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()
}
Roundreturns the result of roundingtto the nearest multiple ofd(since the zero time). The rounding behavior for halfway values is to round up. Ifd <= 0,Roundreturnststripped of any monotonic clock reading but otherwise unchanged.
Roundoperates 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.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.