golang.org/x/build@v0.0.0-20240506185731-218518f32b70/cmd/greplogs/timeflag.go (about) 1 // Copyright 2021 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "flag" 9 "time" 10 ) 11 12 const ( 13 rfc3339Date = "2006-01-02" 14 rfc3339DateTime = "2006-01-02T15:04:05" 15 ) 16 17 // A timeFlag is a flag.Getter that parses a time.Time 18 // from either an RFC-3339 date or an RFC-3339 date and time. 19 // 20 // Fractional seconds and explicit time zones are not allowed. 21 type timeFlag struct { 22 Time time.Time 23 } 24 25 var _ = flag.Getter((*timeFlag)(nil)) 26 27 func (tf *timeFlag) Set(s string) error { 28 if s == "" { 29 tf.Time = time.Time{} 30 return nil 31 } 32 33 t, err := time.Parse(rfc3339Date, s) 34 if err != nil { 35 t, err = time.Parse(rfc3339DateTime, s) 36 } 37 if err == nil { 38 tf.Time = t 39 } 40 return err 41 } 42 43 func (tf *timeFlag) String() string { 44 if tf.Time.IsZero() { 45 return "" 46 } 47 if tf.Time.Hour() == 0 && tf.Time.Minute() == 0 && tf.Time.Second() == 0 { 48 return tf.Time.Format(rfc3339Date) 49 } 50 return tf.Time.Format(rfc3339DateTime) 51 } 52 53 func (tf *timeFlag) Get() interface{} { 54 return tf.Time 55 }