Skip to content

Commit

Permalink
jsontime: add Get and Int duration helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Jan 10, 2025
1 parent 0493223 commit 64d4dbb
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions jsontime/duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ func S(dur time.Duration) Seconds {
return Seconds{Duration: dur}
}

func SInt(dur int) Seconds {
return Seconds{Duration: time.Duration(dur) * time.Second}
}

func (s Seconds) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(int64(s.Seconds()), 10)), nil
}
Expand All @@ -54,6 +58,13 @@ func (s *Seconds) Scan(src interface{}) error {
return anyIntegerToDuration(src, time.Second, &s.Duration)
}

func (s *Seconds) Get() time.Duration {
if s == nil {
return 0
}
return s.Duration
}

type Milliseconds struct {
time.Duration
}
Expand All @@ -62,6 +73,10 @@ func MS(dur time.Duration) Milliseconds {
return Milliseconds{Duration: dur}
}

func MSInt(dur int64) Milliseconds {
return Milliseconds{Duration: time.Duration(dur) * time.Millisecond}
}

func (s Milliseconds) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(s.Milliseconds(), 10)), nil
}
Expand All @@ -78,6 +93,13 @@ func (s *Milliseconds) Scan(src interface{}) error {
return anyIntegerToDuration(src, time.Millisecond, &s.Duration)
}

func (s *Milliseconds) Get() time.Duration {
if s == nil {
return 0
}
return s.Duration
}

type Microseconds struct {
time.Duration
}
Expand All @@ -98,6 +120,13 @@ func (s *Microseconds) Scan(src interface{}) error {
return anyIntegerToDuration(src, time.Microsecond, &s.Duration)
}

func (s *Microseconds) Get() time.Duration {
if s == nil {
return 0
}
return s.Duration
}

type Nanoseconds struct {
time.Duration
}
Expand All @@ -117,3 +146,10 @@ func (s *Nanoseconds) UnmarshalJSON(data []byte) error {
func (s *Nanoseconds) Scan(src interface{}) error {
return anyIntegerToDuration(src, time.Nanosecond, &s.Duration)
}

func (s *Nanoseconds) Get() time.Duration {
if s == nil {
return 0
}
return s.Duration
}

0 comments on commit 64d4dbb

Please sign in to comment.