-
Notifications
You must be signed in to change notification settings - Fork 124
/
time.go
70 lines (57 loc) · 1.51 KB
/
time.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package model
import (
"io"
"strconv"
"strings"
"time"
"github.com/99designs/gqlgen/graphql"
"github.com/evergreen-ci/utility"
"github.com/mongodb/grip"
"github.com/pkg/errors"
)
const (
// APITimeFormat defines ISO-8601 UTC with 3 fractional seconds behind a dot
// specified by the API spec document.
APITimeFormat = "\"2006-01-02T15:04:05.000Z\""
)
func ParseTime(tval string) (time.Time, error) {
if !strings.HasPrefix(tval, "\"") {
tval = "\"" + tval + "\""
}
t, err := time.ParseInLocation(APITimeFormat, tval, time.UTC)
return t, errors.WithStack(err)
}
// Represents duration in milliseconds
type APIDuration uint64
func NewAPIDuration(d time.Duration) APIDuration {
return APIDuration(d / time.Millisecond)
}
func (i APIDuration) ToDuration() time.Duration {
return time.Duration(i) * time.Millisecond
}
func MarshalAPIDuration(b APIDuration) graphql.Marshaler {
return graphql.WriterFunc(func(w io.Writer) {
_, err := w.Write([]byte(strconv.FormatInt(int64(b), 10)))
grip.Error(err)
})
}
func UnmarshalAPIDuration(v interface{}) (APIDuration, error) {
switch v := v.(type) {
case int:
return APIDuration(v), nil
default:
return APIDuration(0), errors.Errorf("programmatic error: expected an integer duration (in nanoseconds) but got type %T", v)
}
}
func ToTimePtr(t time.Time) *time.Time {
if utility.IsZeroTime(t) {
return nil
}
return &t
}
func FromTimePtr(t *time.Time) (time.Time, error) {
if t == nil {
return time.Time{}, nil
}
return ParseTime(t.Format(APITimeFormat))
}