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

types: fix a bug of FromGoTime when handling rounding #12258

Merged
merged 2 commits into from
Sep 24, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
}

}