-
Notifications
You must be signed in to change notification settings - Fork 24
/
timespan.go
45 lines (37 loc) · 1006 Bytes
/
timespan.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package apigee
import (
"errors"
"strings"
"time"
"strconv"
"fmt"
)
// Timespan represents a timespan that can be parsed from a string like "3d"
// meaning "3 days". It will typically be serialized as milliseconds =
// milliseconds-since-unix-epoch.
type Timespan struct {
time.Duration
}
func NewTimespan(initializer string) *Timespan {
initializer = strings.ToLower(initializer)
if strings.HasSuffix(initializer, "d") {
s := strings.TrimSuffix(initializer, "d")
i, _ := strconv.Atoi(s)
i = i * 24
initializer = fmt.Sprintf("%dh", i)
}
duration, _ := time.ParseDuration(initializer)
return &Timespan{duration}
}
func (span Timespan) MarshalJSON() ([]byte, error) {
s := fmt.Sprintf("%0.f", span.Duration.Seconds()*1000)
return []byte(s), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (span *Timespan) UnmarshalJSON(b []byte) error {
e := errors.New("not supported")
return e
}
func (span Timespan) String() string {
return span.String()
}