Skip to content

Commit

Permalink
mysql: fix cast date to int.
Browse files Browse the repository at this point in the history
  • Loading branch information
overvenus committed Apr 2, 2016
1 parent 8aa1055 commit 0b2c9f9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
12 changes: 11 additions & 1 deletion mysql/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,17 +215,27 @@ func (t *Time) UnmarshalInLocation(b []byte, loc *time.Location) error {
}

const numberFormat = "20060102150405"
const dateFormat = "20060102"

// ToNumber returns a formatted number.
// e.g,
// 2012-12-12 -> 20121212
// 2012-12-12T10:10:10 -> 20121212101010
// 2012-12-12T10:10:10.123456 -> 20121212101010.123456
func (t Time) ToNumber() Decimal {
if t.IsZero() {
return ZeroDecimal
}

tfStr := numberFormat
// Fix issue #1046
// Prevents from converting 2012-12-12 to 20121212000000
var tfStr string
if t.Type == TypeDate {
tfStr = dateFormat
} else {
tfStr = numberFormat
}

if t.Fsp > 0 {
tfStr = fmt.Sprintf("%s.%s", tfStr, strings.Repeat("0", t.Fsp))
}
Expand Down
23 changes: 23 additions & 0 deletions mysql/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,29 @@ func (s *testTimeSuite) TestToNumber(c *C) {
c.Assert(t.ToNumber().String(), Equals, test.Expect)
}

// Fix issue #1046
tblDate := []struct {
Input string
Fsp int
Expect string
}{
{"12-12-31 11:30:45", 0, "20121231"},
{"12-12-31 11:30:45", 6, "20121231"},
{"12-12-31 11:30:45.123", 6, "20121231"},
{"12-12-31 11:30:45.123345", 0, "20121231"},
{"12-12-31 11:30:45.123345", 3, "20121231"},
{"12-12-31 11:30:45.123345", 5, "20121231"},
{"12-12-31 11:30:45.123345", 6, "20121231"},
{"12-12-31 11:30:45.1233457", 6, "20121231"},
{"12-12-31 11:30:45.823345", 0, "20121231"},
}

for _, test := range tblDate {
t, err := ParseTime(test.Input, TypeDate, 0)
c.Assert(err, IsNil)
c.Assert(t.ToNumber().String(), Equals, test.Expect)
}

tblDuration := []struct {
Input string
Fsp int
Expand Down

0 comments on commit 0b2c9f9

Please sign in to comment.