-
Notifications
You must be signed in to change notification settings - Fork 11
/
now.go
66 lines (52 loc) · 1.46 KB
/
now.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
package dates
import (
"time"
)
// Now returns the time now.. according to the current source of now
func Now() time.Time {
return currentNowSource.Now()
}
// Since returns the time elapsed since t
func Since(t time.Time) time.Duration {
return Now().Sub(t)
}
// NowSource is something that can provide a now result
type NowSource interface {
Now() time.Time
}
// defaultNowSource returns now as the current system time
type defaultNowSource struct{}
func (s defaultNowSource) Now() time.Time {
return time.Now()
}
// DefaultNowSource is the default time source
var DefaultNowSource NowSource = defaultNowSource{}
var currentNowSource = DefaultNowSource
// SetNowSource sets the time source used by Now()
func SetNowSource(source NowSource) {
currentNowSource = source
}
// a source which returns a fixed time
type fixedNowSource struct {
now time.Time
}
func (s *fixedNowSource) Now() time.Time {
return s.now
}
// NewFixedNowSource creates a new fixed time now source
func NewFixedNowSource(now time.Time) NowSource {
return &fixedNowSource{now: now}
}
// a now source which returns a sequence of times 1 second after each other
type sequentialNowSource struct {
current time.Time
}
func (s *sequentialNowSource) Now() time.Time {
now := s.current
s.current = s.current.Add(time.Second * 1)
return now
}
// NewSequentialNowSource creates a new sequential time source
func NewSequentialNowSource(start time.Time) NowSource {
return &sequentialNowSource{current: start}
}