-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdate.go
More file actions
53 lines (44 loc) · 1.01 KB
/
Copy pathdate.go
File metadata and controls
53 lines (44 loc) · 1.01 KB
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
package metadata
import (
"fmt"
"time"
"gopkg.in/yaml.v3"
)
// Date subscribe the publication date.
//
// A string value in YYYY-MM-DD format. (Only the year is necessary.)
type Date string
// UnmarshalYAML implement yaml.Unmarshaler interface.
func (date *Date) UnmarshalYAML(value *yaml.Node) (err error) {
var d string
if err = value.Decode(&d); err != nil {
return err
}
// check data format
if err := checkDateFormat(d); err != nil {
return err
}
*date = Date(d)
return nil
}
// MarshalYAML implement yaml.Marshaler interface.
func (date Date) MarshalYAML() (interface{}, error) {
var d = string(date)
if err := checkDateFormat(d); err != nil {
return nil, err
}
return d, nil
}
func checkDateFormat(d string) (err error) {
// check data format
var dateTime time.Time
for _, layout := range []string{"2006-01-02", "2006-01", "2006", time.RFC3339} {
if dateTime, err = time.Parse(layout, d); err == nil {
break
}
}
if dateTime.IsZero() {
return fmt.Errorf("bad date %v", d)
}
return nil
}