From 481e12aec6c458eaaabf82d247837d4fb8ca401d Mon Sep 17 00:00:00 2001 From: Jasper Bok Date: Fri, 14 Jul 2023 18:00:14 +0200 Subject: [PATCH] Add custom `Time` type to unmarshal Jira's times --- comment.go | 14 +++++--------- time.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) create mode 100644 time.go diff --git a/comment.go b/comment.go index d490d9c..8729116 100644 --- a/comment.go +++ b/comment.go @@ -1,13 +1,9 @@ package jiraclient -import ( - "time" -) - type Comment struct { - Self string `json:"self"` - Id string `json:"id"` - Author User `json:"author"` - Body string `json:"body"` - Created time.Time `json:created"` + Self string `json:"self"` + Id string `json:"id"` + Author User `json:"author"` + Body string `json:"body"` + Created Time `json:"created"` } diff --git a/time.go b/time.go new file mode 100644 index 0000000..a92629c --- /dev/null +++ b/time.go @@ -0,0 +1,28 @@ +package jiraclient + +import ( + "fmt" + "strings" + "time" +) + +const jiraTimeLayout = "2006-01-02T15:04:05-0700" + +type Time struct { + time.Time +} + +func (t *Time) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf("\"%s\"", t.Time.Format(jiraTimeLayout))), nil +} + +func (t *Time) UnmarshalJSON(data []byte) error { + s := strings.Trim(string(data), "\"") + if s == "null" || s == "" { + return nil + } + + parsedTime, err := time.Parse(jiraTimeLayout, s) + t.Time = parsedTime + return err +}