-
Notifications
You must be signed in to change notification settings - Fork 44
/
datetime.go
57 lines (47 loc) · 1.1 KB
/
datetime.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
package timeout
import (
"database/sql/driver"
"fmt"
"strings"
"time"
)
type DateTime time.Time
const DateTimeFormat = "2006-01-02 15:04:05"
func (d *DateTime) UnmarshalJSON(src []byte) error {
return d.UnmarshalText(strings.Replace(string(src), "\"", "", -1))
}
func (d DateTime) MarshalJSON() ([]byte, error) {
return []byte(`"` + d.String() + `"`), nil
}
func (d *DateTime) UnmarshalText(value string) error {
dd, err := time.Parse(DateTimeFormat, value)
if err != nil {
return err
}
*d = DateTime(dd)
return nil
}
func (d DateTime) String() string {
return (time.Time)(d).Format(DateTimeFormat)
}
func (d *DateTime) Scan(value interface{}) error {
switch v := value.(type) {
case []byte:
return d.UnmarshalText(string(v))
case string:
return d.UnmarshalText(v)
case time.Time:
*d = DateTime(v)
case nil:
*d = DateTime{}
default:
return fmt.Errorf("cannot sql.Scan() DBDate from: %#v", v)
}
return nil
}
func (d DateTime) Value() (driver.Value, error) {
return driver.Value(time.Time(d).Format(DateTimeFormat)), nil
}
func (DateTime) GormDataType() string {
return "DATETIME"
}