-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
day_time.go
100 lines (83 loc) · 2 KB
/
day_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
100
package jsonx
import (
"fmt"
"strconv"
"strings"
"time"
)
const (
// DayTimeLayout holds the time layout for the the format of "hour:minute:second", hour can be 15, meaning 3 PM.
DayTimeLayout = "15:04:05"
)
// DayTime describes a time compatible with DayTimeLayout.
type DayTime time.Time
// ParseDayTime reads from "s" and returns the DayTime time.
func ParseDayTime(s string) (DayTime, error) {
if s == "" || s == "null" {
return DayTime{}, nil
}
tt, err := time.Parse(DayTimeLayout, s)
if err != nil {
return DayTime{}, err
}
return DayTime(tt), nil
}
// UnmarshalJSON parses the "b" into DayTime time.
func (t *DayTime) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return nil
}
s := strings.Trim(string(b), `"`)
tt, err := ParseDayTime(s)
if err != nil {
return err
}
*t = tt
return nil
}
// MarshalJSON writes a quoted string in the DayTime time format.
func (t DayTime) MarshalJSON() ([]byte, error) {
if s := t.String(); s != "" {
s = strconv.Quote(s)
return []byte(s), nil
}
return nullLiteral, nil // Note: if the front-end wants an empty string instead I must change that.
}
// ToTime returns the unwrapped *t to time.Time.
func (t *DayTime) ToTime() time.Time {
tt := time.Time(*t)
return tt
}
// IsZero reports whether "t" is zero time.
func (t DayTime) IsZero() bool {
return time.Time(t).IsZero()
}
// String returns the text representation of the "t" using the DayTime time layout.
func (t DayTime) String() string {
tt := t.ToTime()
if tt.IsZero() {
return ""
}
return tt.Format(DayTimeLayout)
}
// Scan completes the sql driver.Scanner interface.
func (t *DayTime) Scan(src interface{}) error {
switch v := src.(type) {
case time.Time: // type was set to timestamp
if v.IsZero() {
return nil // don't set zero, ignore it.
}
*t = DayTime(v)
case string:
tt, err := ParseDayTime(v)
if err != nil {
return err
}
*t = tt
case nil:
*t = DayTime(time.Time{})
default:
return fmt.Errorf("DayTime: unknown type of: %T", v)
}
return nil
}