-
Notifications
You must be signed in to change notification settings - Fork 0
/
date.go
executable file
·97 lines (80 loc) · 1.79 KB
/
date.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
package odt
import (
"database/sql/driver"
"errors"
"fmt"
"strings"
"time"
)
const DefaultLayout = "2006-01-02"
var dateLayout = DefaultLayout
type Date struct {
*time.Time
}
func SetDateFormat(f string) {
dateLayout = f
}
func GetDateFormat() string {
return dateLayout
}
func NewDate(t time.Time) *Date {
return &Date{&t}
}
func (d *Date) UnmarshalJSON(b []byte) (err error) {
s := strings.Trim(string(b), "\"")
if s == "null" {
d.Time = nil
return
}
t, err := time.Parse(dateLayout, s)
d.Time = &t
return
}
func (d Date) MarshalJSON() ([]byte, error) {
if d.Time == nil {
return []byte("null"), nil
}
return []byte(fmt.Sprintf("\"%s\"", d.Time.Format(dateLayout))), nil
}
func (d Date) Value() (driver.Value, error) {
if d.Time == nil {
return driver.Value(nil), nil
}
return driver.Value(*d.Time), nil
}
// Scan - Implement the database/sql scanner interface
func (d *Date) Scan(value interface{}) error {
// if value is nil
if value == nil {
*d = Date{nil}
return nil
}
if bv, err := convertDateValue(value); err == nil {
// if this is a time type
if v, ok := bv.(time.Time); ok {
*d = Date{&v}
return nil
}
}
// otherwise, return an error
return errors.New("failed to scan date.Date")
}
func convertDateValue(src interface{}) (driver.Value, error) {
switch s := src.(type) {
case time.Time:
return s, nil
case string:
tm, err := time.Parse(DefaultLayout, s)
if err != nil {
return nil, fmt.Errorf("sql/driver: couldn't convert %q into type Date", s)
}
return tm, nil
case []byte:
tm, err := time.Parse(DefaultLayout, string(s))
if err != nil {
return nil, fmt.Errorf("sql/driver: couldn't convert %q into type Date", s)
}
return tm, nil
}
return nil, fmt.Errorf("sql/driver: couldn't convert %v (%T) into type Date", src, src)
}