-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
64 lines (53 loc) · 1.65 KB
/
types.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
package cbl
import (
"errors"
"time"
)
const (
DateFormat = "20060102"
DateTimeFormat = "20060102T15:04:05"
)
type Date struct {
Time time.Time
}
// MarshalText implements the encoding.TextMarshaler interface.
// The time is formatted in YYYYMMDD format.
func (d Date) MarshalText() ([]byte, error) {
if y := d.Time.Year(); y < 0 || y >= 10000 {
return nil, errors.New("Time.MarshalText: year outside of range [0,9999]")
}
b := make([]byte, 0, len(DateFormat))
return d.Time.AppendFormat(b, DateFormat), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
// The time is expected to be in YYYYMMDD format.
func (d *Date) UnmarshalText(data []byte) error {
// Fractional seconds are handled implicitly by Parse.
var err error
(*d).Time, err = time.Parse(DateFormat, string(data))
return err
}
type DateTime struct {
Time time.Time
}
// MarshalText implements the encoding.TextMarshaler interface.
// The time is formatted in YYYYMMDDTHH:MM:SS format.
func (d DateTime) MarshalText() ([]byte, error) {
if y := d.Time.Year(); y < 0 || y >= 10000 {
return nil, errors.New("Time.MarshalText: year outside of range [0,9999]")
}
b := make([]byte, 0, len(DateTimeFormat))
return d.Time.AppendFormat(b, DateTimeFormat), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
// The time is expected to be in YYYYMMDDTHH:MM:SS format.
func (d *DateTime) UnmarshalText(data []byte) error {
// Fractional seconds are handled implicitly by Parse.
var err error
(*d).Time, err = time.Parse(DateTimeFormat, string(data))
if err == nil {
return nil
}
(*d).Time, err = time.Parse(DateFormat, string(data))
return err
}