You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The time library's "Truncate" method is clearly documented to operate since the zero time (i.e. in UTC). It would be useful if the library also included a function to operate in the scope of the time's current Location. Otherwise, one has to code one's own solution to get, for example, the midnight time of a given time:
I don't think midnight is a compelling example. The vast majority of truncation/rounding of times happens on units of 1 hour or smaller, and those are typically not sensitive to time zone. Round and Truncate had to specify a zone for calls that pass in larger durations, but it does not seem to be worth additional methods.
For the motivating example of finding midnight, truncation doesn't even work. The obvious call is Truncate(24*time.Hour). That means to return a time that is a multiple of 24 hours since some base time (presumably derived from the location). But in any location with daylight savings, if you just consider times that are 24 hours apart from each other starting with some midnight, for half the year you'll be getting 11pm or 1am depending on when you started and where you are.
If you want to find midnight (or in general change to a specific time on the same day), use:
yy, mm, dd := t.Date()
t = time.Date(yy, mm, dd, 0, 0, 0, 0, t.Location())
The time library's "Truncate" method is clearly documented to operate since the zero time (i.e. in UTC). It would be useful if the library also included a function to operate in the scope of the time's current Location. Otherwise, one has to code one's own solution to get, for example, the midnight time of a given time:
func midnightOf(t time.Time) time.Time {
d := time.Duration(-t.Hour()) * time.Hour +
time.Duration(-t.Minute()) * time.Minute +
time.Duration(-t.Second()) * time.Second +
time.Duration(-t.Nanosecond) * time.Nanosecond
return t.Add(d)
}
The text was updated successfully, but these errors were encountered: