blob: 987deabb5e809053fec2e51a640607591249af3e [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001// Copyright 2015 go-swagger maintainers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package strfmt
16
17import (
18 "database/sql/driver"
19 "errors"
20 "fmt"
21 "regexp"
22 "strings"
23 "time"
24
25 "github.com/globalsign/mgo/bson"
26 "github.com/mailru/easyjson/jlexer"
27 "github.com/mailru/easyjson/jwriter"
28)
29
30func init() {
31 dt := DateTime{}
32 Default.Add("datetime", &dt, IsDateTime)
33}
34
35// IsDateTime returns true when the string is a valid date-time
36func IsDateTime(str string) bool {
37 if len(str) < 4 {
38 return false
39 }
40 s := strings.Split(strings.ToLower(str), "t")
41 if len(s) < 2 || !IsDate(s[0]) {
42 return false
43 }
44
45 matches := rxDateTime.FindAllStringSubmatch(s[1], -1)
46 if len(matches) == 0 || len(matches[0]) == 0 {
47 return false
48 }
49 m := matches[0]
50 res := m[1] <= "23" && m[2] <= "59" && m[3] <= "59"
51 return res
52}
53
54const (
55 // RFC3339Millis represents a ISO8601 format to millis instead of to nanos
56 RFC3339Millis = "2006-01-02T15:04:05.000Z07:00"
57 // RFC3339Micro represents a ISO8601 format to micro instead of to nano
58 RFC3339Micro = "2006-01-02T15:04:05.000000Z07:00"
59 // DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6
60 DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$`
61)
62
63var (
64 dateTimeFormats = []string{RFC3339Micro, RFC3339Millis, time.RFC3339, time.RFC3339Nano}
65 rxDateTime = regexp.MustCompile(DateTimePattern)
66 // MarshalFormat sets the time resolution format used for marshaling time (set to milliseconds)
67 MarshalFormat = RFC3339Millis
68)
69
70// ParseDateTime parses a string that represents an ISO8601 time or a unix epoch
71func ParseDateTime(data string) (DateTime, error) {
72 if data == "" {
73 return NewDateTime(), nil
74 }
75 var lastError error
76 for _, layout := range dateTimeFormats {
77 dd, err := time.Parse(layout, data)
78 if err != nil {
79 lastError = err
80 continue
81 }
82 lastError = nil
83 return DateTime(dd), nil
84 }
85 return DateTime{}, lastError
86}
87
88// DateTime is a time but it serializes to ISO8601 format with millis
89// It knows how to read 3 different variations of a RFC3339 date time.
90// Most APIs we encounter want either millisecond or second precision times.
91// This just tries to make it worry-free.
92//
93// swagger:strfmt date-time
94type DateTime time.Time
95
96// NewDateTime is a representation of zero value for DateTime type
97func NewDateTime() DateTime {
98 return DateTime(time.Unix(0, 0).UTC())
99}
100
101// String converts this time to a string
102func (t DateTime) String() string {
103 return time.Time(t).Format(MarshalFormat)
104}
105
106// MarshalText implements the text marshaller interface
107func (t DateTime) MarshalText() ([]byte, error) {
108 return []byte(t.String()), nil
109}
110
111// UnmarshalText implements the text unmarshaller interface
112func (t *DateTime) UnmarshalText(text []byte) error {
113 tt, err := ParseDateTime(string(text))
114 if err != nil {
115 return err
116 }
117 *t = tt
118 return nil
119}
120
121// Scan scans a DateTime value from database driver type.
122func (t *DateTime) Scan(raw interface{}) error {
123 // TODO: case int64: and case float64: ?
124 switch v := raw.(type) {
125 case []byte:
126 return t.UnmarshalText(v)
127 case string:
128 return t.UnmarshalText([]byte(v))
129 case time.Time:
130 *t = DateTime(v)
131 case nil:
132 *t = DateTime{}
133 default:
134 return fmt.Errorf("cannot sql.Scan() strfmt.DateTime from: %#v", v)
135 }
136
137 return nil
138}
139
140// Value converts DateTime to a primitive value ready to written to a database.
141func (t DateTime) Value() (driver.Value, error) {
142 return driver.Value(t.String()), nil
143}
144
145// MarshalJSON returns the DateTime as JSON
146func (t DateTime) MarshalJSON() ([]byte, error) {
147 var w jwriter.Writer
148 t.MarshalEasyJSON(&w)
149 return w.BuildBytes()
150}
151
152// MarshalEasyJSON writes the DateTime to a easyjson.Writer
153func (t DateTime) MarshalEasyJSON(w *jwriter.Writer) {
154 w.String(time.Time(t).Format(MarshalFormat))
155}
156
157// UnmarshalJSON sets the DateTime from JSON
158func (t *DateTime) UnmarshalJSON(data []byte) error {
159 l := jlexer.Lexer{Data: data}
160 t.UnmarshalEasyJSON(&l)
161 return l.Error()
162}
163
164// UnmarshalEasyJSON sets the DateTime from a easyjson.Lexer
165func (t *DateTime) UnmarshalEasyJSON(in *jlexer.Lexer) {
166 if data := in.String(); in.Ok() {
167 tt, err := ParseDateTime(data)
168 if err != nil {
169 in.AddError(err)
170 return
171 }
172 *t = tt
173 }
174}
175
176// GetBSON returns the DateTime as a bson.M{} map.
177func (t *DateTime) GetBSON() (interface{}, error) {
178 return bson.M{"data": t.String()}, nil
179}
180
181// SetBSON sets the DateTime from raw bson data
182func (t *DateTime) SetBSON(raw bson.Raw) error {
183 var m bson.M
184 if err := raw.Unmarshal(&m); err != nil {
185 return err
186 }
187
188 if data, ok := m["data"].(string); ok {
189 var err error
190 *t, err = ParseDateTime(data)
191 return err
192 }
193
194 return errors.New("couldn't unmarshal bson raw value as Duration")
195}