From a27d5c38d758facecb0eac8d5f36b0d2c6b9a315 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Fri, 31 Dec 2021 22:59:13 -0500 Subject: [PATCH] times are now unix dates over ints --- pttodo/ts.go | 25 ++++++++++++++++++++++++- pttodo/ts_test.go | 7 +++---- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/pttodo/ts.go b/pttodo/ts.go index 7e7c92c..6d671b3 100644 --- a/pttodo/ts.go +++ b/pttodo/ts.go @@ -2,7 +2,10 @@ package pttodo import ( "encoding/json" + "errors" "time" + + yaml "gopkg.in/yaml.v2" ) type TS int64 @@ -23,5 +26,25 @@ func (ts TS) MarshalYAML() (interface{}, error) { if ts == 0 { ts = TS(time.Now().Unix()) } - return int64(ts), nil + t := time.Unix(int64(ts), 0) + return t.Format(time.UnixDate), nil +} + +func (ts *TS) UnmarshalJSON(b []byte) error { + return yaml.Unmarshal(b, ts) +} + +func (ts *TS) UnmarshalYAML(unmarshaller func(interface{}) error) error { + var n int64 + if err := unmarshaller(&n); err == nil { + *ts = TS(n) + return nil + } + var s string + if err := unmarshaller(&s); err == nil { + t, err := time.Parse(time.UnixDate, s) + *ts = TS(t.Unix()) + return err + } + return errors.New("illegal TS") } diff --git a/pttodo/ts_test.go b/pttodo/ts_test.go index 5502475..566d5fc 100644 --- a/pttodo/ts_test.go +++ b/pttodo/ts_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "strings" "testing" - "time" yaml "gopkg.in/yaml.v2" ) @@ -14,7 +13,7 @@ func TestTSMarshalYaml(t *testing.T) { var ts TS if b, err := yaml.Marshal(TS(5)); err != nil { t.Fatal(err) - } else if s := string(b); strings.TrimSpace(s) != `5` { + } else if s := string(b); !strings.HasSuffix(strings.TrimSpace(s), ` 1969`) { t.Fatal(s) } else if err := yaml.Unmarshal(b, &ts); err != nil { t.Fatal(err) @@ -37,7 +36,7 @@ func TestTSMarshalYaml(t *testing.T) { } func TestJSONTS(t *testing.T) { - ts := TS(time.Now().Unix()) + ts := TS(1234567890) js, err := json.Marshal(ts) if err != nil { t.Fatal(err) @@ -48,7 +47,7 @@ func TestJSONTS(t *testing.T) { t.Fatal(err) } if ts != ts2 { - t.Fatal(ts2) + t.Fatalf("want: %v, got: %v", ts, ts2) } if err := json.Unmarshal([]byte(`123`), &ts2); err != nil {