-
Notifications
You must be signed in to change notification settings - Fork 1
/
timestamp.go
49 lines (40 loc) · 1.06 KB
/
timestamp.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 timestamp
import (
"time"
)
// ToTimestamp generates a millisecond timestamp from the time object.
func ToTimestamp(t time.Time) Timestamp {
return Timestamp{
TimeUnixMs: uint64(t.UnixNano() / 1000000),
}
}
// ToTime generates a time object from a millisecond timestamp.
func ToTime(t uint64) time.Time {
return time.Unix(0, int64(t)*1000000).UTC()
}
// ToTime converts the Timestamp to a time.Time
func (t *Timestamp) ToTime() time.Time {
return ToTime(t.GetTimeUnixMs())
}
// Now returns a timestamp for now.
func Now() Timestamp {
return ToTimestamp(time.Now().UTC())
}
// Clone copies the timestamp.
func (t *Timestamp) Clone() *Timestamp {
if t == nil {
return nil
}
return &Timestamp{TimeUnixMs: t.TimeUnixMs}
}
// Equals checks if the timestamp equals another timestamp.
func (t *Timestamp) Equals(ot *Timestamp) bool {
return t.GetTimeUnixMs() == ot.GetTimeUnixMs()
}
// Validate checks the timestamp.
func (t *Timestamp) Validate(allowEmpty bool) error {
if !allowEmpty && t.GetTimeUnixMs() == 0 {
return ErrEmptyTimestamp
}
return nil
}