-
Notifications
You must be signed in to change notification settings - Fork 0
/
localTime.go
61 lines (53 loc) · 1.19 KB
/
localTime.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
package types
import (
"database/sql/driver"
"fmt"
"time"
)
var (
// DefaultTimeLayout DefaultTimeLayout
DefaultTimeLayout string = "2006年01月02日 15:04:05"
)
type (
// LocalTime LocalTime
LocalTime struct {
time.Time
}
)
func (t *LocalTime) localLayout() string {
return "2006年01月02日 15:04:05"
}
// MarshalJSON json格式化时间的方法
func (t LocalTime) MarshalJSON() ([]byte, error) {
var stamp = fmt.Sprintf("\"%s\"", time.Time(t.Time).Format(t.localLayout()))
// var stamp = fmt.Sprintf("%d", time.Time(t.Time).Unix())
return []byte(stamp), nil
}
// UnmarshalJSON UnmarshalJSON
func (t *LocalTime) UnmarshalJSON(b []byte) error {
var str = string(b)
fmt.Printf(str + "\n")
tTime, err := time.Parse(`"`+t.localLayout()+`"`, str)
if err != nil {
fmt.Println(err)
}
t.Time = tTime
return nil
}
// Value Value
func (t LocalTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
// Scan Scan
func (t *LocalTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = LocalTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}