-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_time.go
99 lines (80 loc) · 1.82 KB
/
custom_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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package models
import (
"strconv"
"strings"
)
/*CustomTime is used to compare times. */
type CustomTime struct {
Value string
Hour int
Min int
}
/*SetTime uses a time string of format '12:50'. If value is a valid time it sets hour and min. */
func (t1 *CustomTime) SetTime(value string) (success bool) {
s := strings.Split(value, ":")
h, err := strconv.Atoi(s[0])
if err != nil {
log.Error("cannot convert value to hour", "value", value,
"error", err.Error())
return
}
m, err := strconv.Atoi(s[1])
if err != nil {
log.Error("cannot convert value to minute", "value", value,
"error", err.Error())
return
}
if 0 <= h && h <= 24 && 0 <= m && m < 60 {
success = true
t1.Value = value
t1.Hour = h
t1.Min = m
}
return
}
/*Before checks if t1 is before or equal (<=) t2. */
func (t1 *CustomTime) Before(t2 *CustomTime) (before bool) {
if t1.Hour < t2.Hour {
before = true
return
}
if t1.Hour == t2.Hour && t1.Min <= t2.Min {
before = true
}
return
}
/*After checks if t1 is after (>) t2. */
func (t1 *CustomTime) After(t2 *CustomTime) (after bool) {
return !t1.Before(t2)
}
/*Sub returns the time interval between two times. */
func (t1 *CustomTime) Sub(t2 *CustomTime) (min int) {
if t1.After(t2) {
min = (t1.Hour-t2.Hour)*60 + (t1.Min - t2.Min)
} else {
min = (t2.Hour-t1.Hour)*60 + (t2.Min - t1.Min)
}
return
}
/*Equals checks if t1 equals t2. */
func (t1 *CustomTime) Equals(t2 *CustomTime) (equals bool) {
if t1.Hour == t2.Hour && t1.Min == t2.Min {
return true
}
return
}
/*String sets the value field of the CustomTime struct. */
func (t1 *CustomTime) String() {
h := strconv.Itoa(t1.Hour)
m := strconv.Itoa(t1.Min)
if t1.Hour < 10 {
t1.Value = "0" + h
} else {
t1.Value = h
}
if t1.Min < 10 {
t1.Value = t1.Value + ":0" + m
} else {
t1.Value = t1.Value + ":" + m
}
}