-
Notifications
You must be signed in to change notification settings - Fork 9
/
time.helper.go
49 lines (44 loc) · 940 Bytes
/
time.helper.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 null
import (
"encoding/json"
"strings"
"time"
)
const (
timeFormat = "2006-01-02 15:04:05"
zeroTime = "1970-01-01 00:00:00"
)
func Parse(x string) (time.Time, error) {
if strings.Index(x, "T") > 0 {
x = strings.Replace(x, "T", " ", 1)
}
switch l := len(x); true {
case l > 19:
x = x[0:19]
if strings.Index(x, "000") == 0 {
x = zeroTime
}
case l == 10:
x += " 00:00:00"
case l == 13:
x += ":00:00"
case l == 16:
x += ":00"
}
return time.ParseInLocation(timeFormat, x, time.Local)
}
// ToDB implements json.Marshaler.
// It will encode null if this time is null.
func (t Time) ToDB() ([]byte, error) {
return t.MarshalJSON()
}
// FromDB implements json.Unmarshaler.
// It supports string, object (e.g. pq.NullTime and friends)
// and null input.
func (t Time) FromDB(data []byte) error {
data, err := json.Marshal(string(data))
if err != nil {
return err
}
return t.UnmarshalJSON(data)
}