forked from Oskang09/goloquent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdate.go
54 lines (46 loc) · 1020 Bytes
/
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
package goloquent
import (
"fmt"
"reflect"
"regexp"
"time"
)
var typeOfDate = reflect.TypeOf(Date(time.Time{}))
// Date :
type Date time.Time
// UnmarshalJSON :
func (d *Date) UnmarshalJSON(b []byte) error {
if b == nil || b2s(b) == "null" {
return nil
}
if !regexp.MustCompile(`^\"\d{4}\-\d{2}\-\d{2}\"$`).Match(b) {
return fmt.Errorf("goloquent: invalid date value %q", b)
}
dt, err := time.Parse("2006-01-02", escape(b))
if err != nil {
return err
}
*d = Date(dt)
return nil
}
// MarshalJSON :
func (d Date) MarshalJSON() ([]byte, error) {
return []byte(`"` + time.Time(d).Format("2006-01-02") + `"`), nil
}
// UnmarshalText :
func (d *Date) UnmarshalText(b []byte) error {
dt, err := time.Parse("2006-01-02", b2s(b))
if err != nil {
return err
}
*d = Date(dt)
return nil
}
// MarshalText :
func (d Date) MarshalText() ([]byte, error) {
return []byte(time.Time(d).Format("2006-01-02")), nil
}
// String :
func (d Date) String() string {
return time.Time(d).Format("2006-01-02")
}