Commit fdb09d28 authored by Hector Chu's avatar Hector Chu

time: fix Time.Add

R=rsc, r
CC=golang-dev
https://golang.org/cl/5448121
parent 1084ab98
......@@ -548,7 +548,7 @@ func (d Duration) Hours() float64 {
func (t Time) Add(d Duration) Time {
t.sec += int64(d / 1e9)
t.nsec += int32(d % 1e9)
if t.nsec > 1e9 {
if t.nsec >= 1e9 {
t.sec++
t.nsec -= 1e9
} else if t.nsec < 0 {
......
......@@ -655,6 +655,17 @@ func TestDaysIn(t *testing.T) {
}
}
func TestAddToExactSecond(t *testing.T) {
// Add an amount to the current time to round it up to the next exact second.
// This test checks that the nsec field still lies within the range [0, 999999999].
t1 := Now()
t2 := t1.Add(Second - Duration(t1.Nanosecond()))
sec := (t1.Second() + 1) % 60
if t2.Second() != sec || t2.Nanosecond() != 0 {
t.Errorf("sec = %d, nsec = %d, want sec = %d, nsec = 0", t2.Second(), t2.Nanosecond(), sec)
}
}
func BenchmarkNow(b *testing.B) {
for i := 0; i < b.N; i++ {
Now()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment