-
Notifications
You must be signed in to change notification settings - Fork 1
/
weekday.go
80 lines (67 loc) · 1.5 KB
/
weekday.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
package time
import (
"database/sql/driver"
"encoding/json"
"strings"
"time"
"github.com/pkg/errors"
)
// Weekday represents day of a week
type Weekday time.Weekday
// Constants representing days of a week
const (
NotAWeekday Weekday = -1 + iota
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
var weekdays = []Weekday{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
// MarshalJSON marshals date to JSON
func (w Weekday) MarshalJSON() ([]byte, error) {
return json.Marshal(w.String())
}
func (w Weekday) String() string {
return strings.ToLower(time.Weekday(w).String())
}
// MarshalText serializes this date type to string
func (w Weekday) MarshalText() ([]byte, error) {
return []byte(w.String()), nil
}
// UnmarshalText parses string into weekday
func (w *Weekday) UnmarshalText(text []byte) error {
if len(text) == 0 {
return nil
}
parsedWeekday, err := ParseWeekday(string(text))
if err != nil {
*w = NotAWeekday
return errors.Wrap(err, "Weekday.UnmarshalText() failed")
}
*w = parsedWeekday
return nil
}
// ParseWeekday parses string into Weekday
func ParseWeekday(weekdayString string) (Weekday, error) {
for _, weekday := range weekdays {
if weekday.String() == strings.ToLower(weekdayString) {
return weekday, nil
}
}
return NotAWeekday, errors.Errorf("Wrong Weekday format: %v", weekdayString)
}
// Value implements the sql driver Valuer interface.
func (w Weekday) Value() (driver.Value, error) {
return strings.ToUpper(w.String()), nil
}