blob: 9521a2ad8729d013ef7c142bef0b7e63fee91e1a [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2016 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package schema
5
6import (
7 "reflect"
8 "time"
9)
10
11// Time returns a Checker that accepts a string value, and returns
12// the parsed time.Time value. Emtpy strings are considered empty times.
13func Time() Checker {
14 return timeC{}
15}
16
17type timeC struct{}
18
19// Coerce implements Checker Coerce method.
20func (c timeC) Coerce(v interface{}, path []string) (interface{}, error) {
21 if v == nil {
22 return nil, error_{"string or time.Time", v, path}
23 }
24 var empty time.Time
25 switch reflect.TypeOf(v).Kind() {
26 case reflect.TypeOf(empty).Kind():
27 return v, nil
28 case reflect.String:
29 vstr := reflect.ValueOf(v).String()
30 if vstr == "" {
31 return empty, nil
32 }
33 v, err := time.Parse(time.RFC3339Nano, vstr)
34 if err != nil {
35 return nil, err
36 }
37 return v, nil
38 default:
39 return nil, error_{"string or time.Time", v, path}
40 }
41}