Skip to content

Commit

Permalink
Merge pull request #15 from monoel69/add_datetime_marshaler
Browse files Browse the repository at this point in the history
Add datetime marshaler
  • Loading branch information
trifonovmixail authored Jul 31, 2023
2 parents 55f77b8 + 5aa9d3b commit d2407ea
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/trifonovmixail/jira-hooks

go 1.19
33 changes: 29 additions & 4 deletions objects/datetime.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,66 @@ import (
"time"
)

const (
dateLayout = "\"2006-01-02\""
timeLayout = "\"2006-01-02T15:04:05.999-0700\""
)

type Time time.Time

func (t *Time) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
return nil
}
ti, err := time.Parse("\"2006-01-02T15:04:05.999-0700\"", string(b))
ti, err := time.Parse(timeLayout, string(b))
if err != nil {
return err
}
*t = Time(ti)
return nil
}

func (t Time) MarshalJSON() ([]byte, error) {
baseTime := time.Time(t)
if baseTime.IsZero() {
return []byte("null"), nil
}
return []byte(baseTime.Format(timeLayout)), nil
}

type Date time.Time

func (d *Date) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
return nil
}
ti, err := time.Parse("\"2006-01-02\"", string(b))
ti, err := time.Parse(dateLayout, string(b))
if err != nil {
return err
}
*d = Date(ti)
return nil
}

func (d Date) MarshalJSON() ([]byte, error) {
date := time.Time(d)
if date.IsZero() {
return []byte("null"), nil
}
return []byte(date.Format(dateLayout)), nil
}

type Timestamp time.Time

func (t *Timestamp) UnmarshalJSON(b []byte) error {
func (ts *Timestamp) UnmarshalJSON(b []byte) error {
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
*t = Timestamp(time.Unix(i, 0))
*ts = Timestamp(time.Unix(i, 0))
return nil
}

func (ts Timestamp) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(time.Time(ts).Unix(), 10)), nil
}

0 comments on commit d2407ea

Please sign in to comment.