We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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.
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.