Skip to content

Commit

Permalink
types: fix a bug of FromGoTime when handling rounding (#12258)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiancaiamao authored and sre-bot committed Sep 24, 2019
1 parent 790b5d5 commit 7e876e1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
6 changes: 4 additions & 2 deletions types/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,10 +195,12 @@ const (

// FromGoTime translates time.Time to mysql time internal representation.
func FromGoTime(t gotime.Time) MysqlTime {
// Plus 500 nanosecond for rounding of the millisecond part.
t = t.Add(500 * gotime.Nanosecond)

year, month, day := t.Date()
hour, minute, second := t.Clock()
// Nanosecond plus 500 then divided 1000 means rounding to microseconds.
microsecond := (t.Nanosecond() + 500) / 1000
microsecond := t.Nanosecond() / 1000
return FromDate(year, int(month), day, hour, minute, second, microsecond)
}

Expand Down
29 changes: 29 additions & 0 deletions types/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1640,3 +1640,32 @@ func (s *testTimeSuite) TestCheckMonthDay(c *C) {
}
}
}

func (s *testTimeSuite) TestFromGoTime(c *C) {
// Test rounding of nanosecond to millisecond.
cases := []struct {
input string
yy int
mm int
dd int
hh int
min int
sec int
micro int
}{
{"2006-01-02T15:04:05.999999999Z", 2006, 1, 2, 15, 4, 6, 0},
{"2006-01-02T15:04:05.999999000Z", 2006, 1, 2, 15, 4, 5, 999999},
{"2006-01-02T15:04:05.999999499Z", 2006, 1, 2, 15, 4, 5, 999999},
{"2006-01-02T15:04:05.999999500Z", 2006, 1, 2, 15, 4, 6, 0},
{"2006-01-02T15:04:05.000000501Z", 2006, 1, 2, 15, 4, 5, 1},
}

for ith, ca := range cases {
t, err := time.Parse(time.RFC3339Nano, ca.input)
c.Assert(err, IsNil)

t1 := types.FromGoTime(t)
c.Assert(t1, Equals, types.FromDate(ca.yy, ca.mm, ca.dd, ca.hh, ca.min, ca.sec, ca.micro), Commentf("idx %d", ith))
}

}

0 comments on commit 7e876e1

Please sign in to comment.