Skip to content

Commit

Permalink
gorp_test: update timestamp parsing code to match reality
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsam committed Oct 4, 2019
1 parent 424f946 commit 833e357
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
3 changes: 3 additions & 0 deletions gorp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2036,6 +2036,9 @@ func TestNullTime(t *testing.T) {

// if time is not null
ts, err := time.Parse(time.Stamp, "Jan 2 15:04:05")
if err != nil {
t.Errorf("failed to parse time %s: %s", time.Stamp, err.Error())
}
ent = &WithNullTime{
Id: 1,
Time: gorp.NullTime{
Expand Down
46 changes: 30 additions & 16 deletions nulltypes.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ package gorp

import (
"database/sql/driver"
"log"
"time"
)

Expand All @@ -24,26 +25,39 @@ type NullTime struct {

// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
log.Printf("Time scan value is: %#v", value)
switch t := value.(type) {
case time.Time:
nt.Time, nt.Valid = t, true
case []byte:
nt.Valid = false
for _, dtfmt := range []string{
"2006-01-02 15:04:05.999999999",
"2006-01-02T15:04:05.999999999",
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02",
"2006-01-02 15:04:05-07:00",
} {
var err error
if nt.Time, err = time.Parse(dtfmt, string(t)); err == nil {
nt.Valid = true
break
}
v := strToTime(string(t))
if v != nil {
nt.Valid = true
nt.Time = *t
}
case string:
v := strToTime(t)
if v != nil {
nt.Valid = true
nt.Time = *t
}
}
return nil
}

func strToTime(v string) *time.Time {
for _, dtfmt := range []string{
"2006-01-02 15:04:05.999999999",
"2006-01-02T15:04:05.999999999",
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02",
"2006-01-02 15:04:05-07:00",
} {
if t, err := time.Parse(dtfmt, v); err == nil {
return &t
}
}
return nil
Expand Down

0 comments on commit 833e357

Please sign in to comment.