Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

time: could use a "truncate in timezone" feature #10894

fixermark opened this issue May 18, 2015 · 1 comment

time: could use a "truncate in timezone" feature #10894

fixermark opened this issue May 18, 2015 · 1 comment


Copy link

@fixermark fixermark commented May 18, 2015

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)

@ianlancetaylor ianlancetaylor changed the title time library could use a "truncate in timezone" feature time: could use a "truncate in timezone" feature May 18, 2015
@ianlancetaylor ianlancetaylor added this to the Go1.6 milestone May 18, 2015
Copy link

@rsc rsc commented Oct 24, 2015

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())
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.