2 Package date provides time.Time derivatives that conform to the Swagger.io (https://swagger.io/)
3 defined date formats: Date and DateTime. Both types may, in most cases, be used in lieu of
4 time.Time types. And both convert to time.Time through a ToTime method.
8 // Copyright 2017 Microsoft Corporation
10 // Licensed under the Apache License, Version 2.0 (the "License");
11 // you may not use this file except in compliance with the License.
12 // You may obtain a copy of the License at
14 // http://www.apache.org/licenses/LICENSE-2.0
16 // Unless required by applicable law or agreed to in writing, software
17 // distributed under the License is distributed on an "AS IS" BASIS,
18 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 // See the License for the specific language governing permissions and
20 // limitations under the License.
28 fullDate = "2006-01-02"
29 fullDateJSON = `"2006-01-02"`
30 dateFormat = "%04d-%02d-%02d"
31 jsonFormat = `"%04d-%02d-%02d"`
34 // Date defines a type similar to time.Time but assumes a layout of RFC3339 full-date (i.e.,
40 // ParseDate create a new Date from the passed string.
41 func ParseDate(date string) (d Date, err error) {
42 return parseDate(date, fullDate)
45 func parseDate(date string, format string) (Date, error) {
46 d, err := time.Parse(format, date)
47 return Date{Time: d}, err
50 // MarshalBinary preserves the Date as a byte array conforming to RFC3339 full-date (i.e.,
52 func (d Date) MarshalBinary() ([]byte, error) {
53 return d.MarshalText()
56 // UnmarshalBinary reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e.,
58 func (d *Date) UnmarshalBinary(data []byte) error {
59 return d.UnmarshalText(data)
62 // MarshalJSON preserves the Date as a JSON string conforming to RFC3339 full-date (i.e.,
64 func (d Date) MarshalJSON() (json []byte, err error) {
65 return []byte(fmt.Sprintf(jsonFormat, d.Year(), d.Month(), d.Day())), nil
68 // UnmarshalJSON reconstitutes the Date from a JSON string conforming to RFC3339 full-date (i.e.,
70 func (d *Date) UnmarshalJSON(data []byte) (err error) {
71 d.Time, err = time.Parse(fullDateJSON, string(data))
75 // MarshalText preserves the Date as a byte array conforming to RFC3339 full-date (i.e.,
77 func (d Date) MarshalText() (text []byte, err error) {
78 return []byte(fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day())), nil
81 // UnmarshalText reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e.,
83 func (d *Date) UnmarshalText(data []byte) (err error) {
84 d.Time, err = time.Parse(fullDate, string(data))
88 // String returns the Date formatted as an RFC3339 full-date string (i.e., 2006-01-02).
89 func (d Date) String() string {
90 return fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day())
93 // ToTime returns a Date as a time.Time
94 func (d Date) ToTime() time.Time {