From 7e876e118aca78dbb0dac53c63e9470d0bf39dfb Mon Sep 17 00:00:00 2001 From: tiancaiamao Date: Tue, 24 Sep 2019 10:28:16 +0800 Subject: [PATCH] types: fix a bug of `FromGoTime` when handling rounding (#12258) --- types/time.go | 6 ++++-- types/time_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/types/time.go b/types/time.go index 253fc537688f3..16fade6e14be0 100644 --- a/types/time.go +++ b/types/time.go @@ -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) } diff --git a/types/time_test.go b/types/time_test.go index 57c6cca351d6f..7a1995f9eee8a 100644 --- a/types/time_test.go +++ b/types/time_test.go @@ -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)) + } + +}