This repository has been archived by the owner on Dec 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datetime.go
78 lines (61 loc) · 1.65 KB
/
datetime.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
71
72
73
74
75
76
77
78
package datetime
import (
"time"
pbdatetime "github.com/altipla-consulting/datetime/altipla/datetime"
"github.com/golang/protobuf/ptypes"
pbtimestamp "github.com/golang/protobuf/ptypes/timestamp"
)
// DiffDays returns the difference between the two dates in days.
func DiffDays(a, b time.Time) int64 {
diff := b.Sub(a)
if diff < 0 {
return int64((diff - 12*time.Hour) / (24 * time.Hour))
}
return int64((diff + 12*time.Hour) / (24 * time.Hour))
}
// TimeToDate returns the remaining time to reach the date.
func TimeToDate(t time.Time) time.Time {
year, month, day := t.Date()
return time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
}
// SerializeDate converts a Go time.Time to proto considering only the date part.
func SerializeDate(t time.Time) *pbdatetime.Date {
if t.IsZero() {
return nil
}
year, month, day := t.Date()
return &pbdatetime.Date{
Day: int32(day),
Month: int32(month),
Year: int32(year),
}
}
// ParseDate converts a proto to Go time.Time.
func ParseDate(date *pbdatetime.Date) time.Time {
if date == nil {
return time.Time{}
}
return time.Date(int(date.Year), time.Month(date.Month), int(date.Day), 0, 0, 0, 0, time.UTC)
}
// SerializeTimestamp converts a Go time.Time to proto.
func SerializeTimestamp(t time.Time) *pbtimestamp.Timestamp {
if t.IsZero() {
return nil
}
result, err := ptypes.TimestampProto(t)
if err != nil {
panic(err)
}
return result
}
// ParseTimestamp converts a proto to Go time.Time.
func ParseTimestamp(timestamp *pbtimestamp.Timestamp) time.Time {
if timestamp == nil {
return time.Time{}
}
t, err := ptypes.Timestamp(timestamp)
if err != nil {
panic(err)
}
return t
}