Reputation: 503
i have time divide by 240m or 4 hour. How to get early time divide by 4 hour starting 00.00 from random time or time.now() ?
Other sample. Divide by 50minutes:
And divider can be starting from 1 second up to 23h59m.
I'm already kind of other approach like https://play.golang.org/p/oJn09DCWqjF but maybe it will be waste the memory of big slice and kind up slow performance if i want to use divider from 2/4 second. Because i want that for experiment expired cache without timer. Thanks.
Upvotes: 0
Views: 143
Reputation: 8222
time.Time.Truncate
is mostly what you want.
It is a little tricky when the time comes with date though, since not all duration can devide 24 hours (for example 50 minutes). You will want to strip the date and add it back.
func truncate(t time.Time, d time.Duration) time.Time {
yy, mm, dd := t.Date()
t = t.AddDate(-yy, -int(mm), -dd)
t = t.Truncate(d)
t = t.AddDate(yy, int(mm), dd)
return t
}
Playground: https://play.golang.org/p/fFAqh_0Wkdp
Please note that playground has a fixed time.
Upvotes: 1