From 10cd2ac7918d2582a4299e3c2d7e15b66aa96bbf Mon Sep 17 00:00:00 2001 From: Felipe Oliveira Date: Tue, 1 Aug 2017 15:32:01 -0300 Subject: [PATCH] subindo dbtime --- dbtime.go | 32 ++++++++++++++++++++++++++ dbtime_test.go | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 dbtime.go create mode 100644 dbtime_test.go diff --git a/dbtime.go b/dbtime.go new file mode 100644 index 000000000..5c96b2744 --- /dev/null +++ b/dbtime.go @@ -0,0 +1,32 @@ +package dbtime + +import ( + "fmt" + "time" +) + +// Time replace MarshalJSON and UnmarshalJSON functions to allow +// compatibility with the Postgresql date format. +type Time struct { + time.Time +} + +const layout = "2006-01-02T15:04:05.999999" + +// UnmarshalJSON compatibility with the Postgresql date format +func (t *Time) UnmarshalJSON(b []byte) (err error) { + if b[0] == '"' && b[len(b)-1] == '"' { + b = b[1 : len(b)-1] + } + if string(b) == `null` { + *t = Time{} + return + } + t.Time, err = time.Parse(layout, string(b)) + return +} + +// MarshalJSON compatibility with the Postgresql date format +func (t Time) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, t.Time.Format(layout))), nil +} diff --git a/dbtime_test.go b/dbtime_test.go new file mode 100644 index 000000000..2f29e14a6 --- /dev/null +++ b/dbtime_test.go @@ -0,0 +1,61 @@ +package dbtime + +import ( + "bytes" + "encoding/json" + "testing" + "time" +) + +type testTime struct { + Date Time `json:"date"` +} + +func TestUnmarshalJSON(t *testing.T) { + var p testTime + j := []byte(`{"date":"2017-05-10T11:00:00.000001"}`) + + err := json.Unmarshal(j, &p) + if err != nil { + t.Fatal(err.Error()) + } + + if p.Date.Time.Unix() != 1494414000 || p.Date.UnixNano() != 1494414000000001000 { + t.Fatal(`Error, incorrect date/time value.`) + } + + j = []byte(`{"date":"null"}`) + err = json.Unmarshal(j, &p) + if err != nil { + t.Fatal(err.Error()) + } + + if !p.Date.IsZero() { + t.Fatal(`Error, p.Date should be zero`) + } +} + +func TestMarshalJSON(t *testing.T) { + var p testTime + var tAux time.Time + var err error + var j []byte + + layout := "2006-01-02T15:04:05.999999" + str := "2017-05-10T11:00:00.000001" + + tAux, err = time.Parse(layout, str) + if err != nil { + t.Fatal(err.Error()) + } + p.Date = Time{tAux} + + j, err = json.Marshal(p) + if err != nil { + t.Fatal(err.Error()) + } + + if !bytes.Equal(j, []byte(`{"date":"2017-05-10T11:00:00.000001"}`)) { + t.Fatal("Error, the date returned is not the same as the date entered.") + } +}