Skip to content

Commit

Permalink
subindo dbtime
Browse files Browse the repository at this point in the history
  • Loading branch information
felipeweb committed Aug 1, 2017
1 parent 5e3ebb9 commit 10cd2ac
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
32 changes: 32 additions & 0 deletions 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
}
61 changes: 61 additions & 0 deletions 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.")
}
}

0 comments on commit 10cd2ac

Please sign in to comment.