Skip to content

Commit

Permalink
add json marshaling to datetime
Browse files Browse the repository at this point in the history
  • Loading branch information
AnteWall committed Apr 19, 2022
1 parent 668c7af commit 70694a9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
15 changes: 13 additions & 2 deletions pkg/insider/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,22 @@ import (

type DateTime time.Time


func (f DateTime) MarshalCSV() ([]byte, error) {
return []byte(f.GetTime().Format(time.RFC3339)), nil
}

func (f *DateTime) MarshalJSON() ([]byte, error) {
return f.GetTime().MarshalJSON()
}

func (f *DateTime) UnmarshalJSON(data []byte) error {
str := string(data)
println(str)
t, err := time.Parse(`"2006-01-02T15:04:05.999999999Z07:00"`, string(data))
*f = DateTime(t)
return err
}

func (f *DateTime) UnmarshalCSV(data []byte) error {
// 31/03/2022 00:00:00
stoTz, err := time.LoadLocation("Europe/Stockholm")
Expand All @@ -27,4 +38,4 @@ func (f *DateTime) UnmarshalCSV(data []byte) error {

func (f DateTime) GetTime() time.Time {
return time.Time(f)
}
}
27 changes: 27 additions & 0 deletions pkg/insider/time_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package insider

import (
"encoding/json"
"github.com/stretchr/testify/assert"
"testing"
"time"
)

func TestDatetime_MarshalJSON(t *testing.T) {
type test struct {
Date DateTime `json:"date"`
}
ti := DateTime(time.Date(2020, 1, 1, 1, 1, 1, 0, time.UTC))
s := test{
Date: ti,
}
marshal, err := json.Marshal(&s)
assert.Nil(t, err)
assert.Equal(t, "{\"date\":\"2020-01-01T01:01:01Z\"}", string(marshal))

s = test{}

err = json.Unmarshal(marshal, &s)
assert.Nil(t, err)
assert.Equal(t, ti, s.Date)
}

0 comments on commit 70694a9

Please sign in to comment.