OLD | NEW |
(Empty) | |
| 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package clockflag |
| 6 |
| 7 import ( |
| 8 "encoding/json" |
| 9 "flag" |
| 10 "time" |
| 11 ) |
| 12 |
| 13 // Time is a flag- and JSON-compatible Time which parses from RFC3339 strings. |
| 14 type Time time.Time |
| 15 |
| 16 var _ interface { |
| 17 flag.Value |
| 18 json.Unmarshaler |
| 19 json.Marshaler |
| 20 } = (*Time)(nil) |
| 21 |
| 22 // Time returns the Time value associated with this Time. |
| 23 func (t Time) Time() time.Time { |
| 24 return time.Time(t) |
| 25 } |
| 26 |
| 27 // Set implements flag.Value. |
| 28 func (t *Time) Set(value string) error { |
| 29 timeValue, err := time.Parse(time.RFC3339Nano, value) |
| 30 if err != nil { |
| 31 return err |
| 32 } |
| 33 *t = Time(timeValue.UTC()) |
| 34 return nil |
| 35 } |
| 36 |
| 37 func (t *Time) String() string { |
| 38 return time.Time(*t).String() |
| 39 } |
| 40 |
| 41 // UnmarshalJSON implements json.Unmarshaler. |
| 42 // |
| 43 // Unmarshals a JSON entry into the underlying type. The entry is expected to |
| 44 // contain a string corresponding to one of the enum's keys. |
| 45 func (t *Time) UnmarshalJSON(data []byte) error { |
| 46 var value time.Time |
| 47 if err := value.UnmarshalJSON(data); err != nil { |
| 48 return err |
| 49 } |
| 50 *t = Time(value.UTC()) |
| 51 return nil |
| 52 } |
| 53 |
| 54 // MarshalJSON implements json.Marshaler. |
| 55 // |
| 56 // Marshals a Time into an RFC3339 time string. |
| 57 func (t Time) MarshalJSON() ([]byte, error) { |
| 58 return t.Time().UTC().MarshalJSON() |
| 59 } |
OLD | NEW |