-
Notifications
You must be signed in to change notification settings - Fork 794
/
time.go
49 lines (40 loc) · 1.18 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
package util
import (
"math"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/weaveworks/common/httpgrpc"
)
const (
nanosecondsInMillisecond = int64(time.Millisecond / time.Nanosecond)
)
func TimeToMillis(t time.Time) int64 {
return t.UnixNano() / nanosecondsInMillisecond
}
// TimeFromMillis is a helper to turn milliseconds -> time.Time
func TimeFromMillis(ms int64) time.Time {
return time.Unix(0, ms*nanosecondsInMillisecond)
}
// ParseTime parses the string into an int64, milliseconds since epoch.
func ParseTime(s string) (int64, error) {
if t, err := strconv.ParseFloat(s, 64); err == nil {
s, ns := math.Modf(t)
tm := time.Unix(int64(s), int64(ns*float64(time.Second)))
return TimeToMillis(tm), nil
}
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
return TimeToMillis(t), nil
}
return 0, httpgrpc.Errorf(http.StatusBadRequest, "cannot parse %q to a valid timestamp", s)
}
func DurationWithJitter(input time.Duration, variancePerc float64) time.Duration {
// No duration? No jitter.
if input == 0 {
return 0
}
variance := int64(float64(input) * variancePerc)
jitter := rand.Int63n(variance*2) - variance
return input + time.Duration(jitter)
}