Debian Codegraph @

util/time.go

raw
1 package util
2
3 import (
4 "errors"
5 "github.com/olebedev/when"
6 "regexp"
7 "strconv"
8 "strings"
9 "time"
10 )
11
12 var (
13 errInvalidDuration = errors.New("unable to parse duration")
14 durationStrRegex = regexp.MustCompile(`(?i)^(\d+)\s*(d|days?|h|hours?|m|mins?|minutes?|s|secs?|seconds?)$`)
15 )
16
17 const (
18 timestampFormat = "2006-01-02T15:04:05.999Z07:00" // Like RFC3339, but with milliseconds
19 )
20
21 // FormatTime formats a time.Time in a RFC339-like format that includes milliseconds
22 func FormatTime(t time.Time) string {
23 return t.Format(timestampFormat)
24 }
25
26 // NextOccurrenceUTC takes a time of day (e.g. 9:00am), and returns the next occurrence
27 // of that time from the current time (in UTC).
28 func NextOccurrenceUTC(timeOfDay, base time.Time) time.Time {
29 hour, minute, seconds := timeOfDay.UTC().Clock()
30 now := base.UTC()
31 next := time.Date(now.Year(), now.Month(), now.Day(), hour, minute, seconds, 0, time.UTC)
32 if next.Before(now) {
33 next = next.AddDate(0, 0, 1)
34 }
35 return next
36 }
37
38 // ParseFutureTime parses a date/time string to a time.Time. It supports unix timestamps, durations
39 // and natural language dates
40 func ParseFutureTime(s string, now time.Time) (time.Time, error) {
41 s = strings.TrimSpace(s)
42 t, err := parseUnixTime(s, now)
43 if err == nil {
44 return t, nil
45 }
46 t, err = parseFromDuration(s, now)
47 if err == nil {
48 return t, nil
49 }
50 t, err = parseNaturalTime(s, now)
51 if err == nil {
52 return t, nil
53 }
54 return time.Time{}, errInvalidDuration
55 }
56
57 // ParseDuration is like time.ParseDuration, except that it also understands days (d), which
58 // translates to 24 hours, e.g. "2d" or "20h".
59 func ParseDuration(s string) (time.Duration, error) {
60 d, err := time.ParseDuration(s)
61 if err == nil {
62 return d, nil
63 }
64 matches := durationStrRegex.FindStringSubmatch(s)
65 if matches != nil {
66 number, err := strconv.Atoi(matches[1])
67 if err != nil {
68 return 0, errInvalidDuration
69 }
70 switch unit := matches[2][0:1]; unit {
71 case "d":
72 return time.Duration(number) * 24 * time.Hour, nil
73 case "h":
74 return time.Duration(number) * time.Hour, nil
75 case "m":
76 return time.Duration(number) * time.Minute, nil
77 case "s":
78 return time.Duration(number) * time.Second, nil
79 default:
80 return 0, errInvalidDuration
81 }
82 }
83 return 0, errInvalidDuration
84 }
85
86 // FormatDuration formats a time.Duration into a human-readable string, e.g. "2d", "20h", "30m", "40s".
87 // It rounds to the largest unit that is not zero, thereby effectively rounding down.
88 func FormatDuration(d time.Duration) string {
89 if d >= 24*time.Hour {
90 return strconv.Itoa(int(d/(24*time.Hour))) + "d"
91 }
92 if d >= time.Hour {
93 return strconv.Itoa(int(d/time.Hour)) + "h"
94 }
95 if d >= time.Minute {
96 return strconv.Itoa(int(d/time.Minute)) + "m"
97 }
98 if d >= time.Second {
99 return strconv.Itoa(int(d/time.Second)) + "s"
100 }
101 return "0s"
102 }
103
104 func parseFromDuration(s string, now time.Time) (time.Time, error) {
105 d, err := ParseDuration(s)
106 if err == nil {
107 return now.Add(d), nil
108 }
109 return time.Time{}, errInvalidDuration
110 }
111
112 func parseUnixTime(s string, now time.Time) (time.Time, error) {
113 t, err := strconv.Atoi(s)
114 if err != nil {
115 return time.Time{}, err
116 } else if int64(t) < now.Unix() {
117 return time.Time{}, errInvalidDuration
118 }
119 return time.Unix(int64(t), 0).UTC(), nil
120 }
121
122 func parseNaturalTime(s string, now time.Time) (time.Time, error) {
123 r, err := when.EN.Parse(s, now) // returns "nil, nil" if no matches!
124 if err != nil || r == nil {
125 return time.Time{}, errInvalidDuration
126 } else if r.Time.After(now) {
127 return r.Time, nil
128 }
129 // Hack: If the time is parsable, but not in the future,
130 // simply append "tomorrow, " to it.
131 r, err = when.EN.Parse("tomorrow, "+s, now) // returns "nil, nil" if no matches!
132 if err != nil || r == nil {
133 return time.Time{}, errInvalidDuration
134 } else if r.Time.After(now) {
135 return r.Time, nil
136 }
137 return time.Time{}, errInvalidDuration
138 }