github.com/wolfi-dev/wolfictl@v0.16.11/pkg/configs/advisory/v2/timestamp.go (about) 1 package v2 2 3 import ( 4 "fmt" 5 "time" 6 7 "gopkg.in/yaml.v3" 8 ) 9 10 // Timestamp is a time.Time that marshals to and from RFC3339 timestamps. 11 type Timestamp time.Time 12 13 // Now returns the current time as a Timestamp. 14 func Now() Timestamp { 15 return Timestamp(time.Now()) 16 } 17 18 const yamlTagTimestamp = "!!timestamp" // see https://yaml.org/type/timestamp.html 19 20 // MarshalYAML implements yaml.Marshaler. 21 func (t Timestamp) MarshalYAML() (interface{}, error) { 22 return yaml.Node{ 23 Kind: yaml.ScalarNode, 24 Tag: yamlTagTimestamp, 25 Value: t.String(), 26 }, nil 27 } 28 29 // UnmarshalYAML implements yaml.Unmarshaler. 30 func (t *Timestamp) UnmarshalYAML(v *yaml.Node) error { 31 if !(v.Kind == yaml.ScalarNode && v.Tag == yamlTagTimestamp) { 32 return fmt.Errorf("expected a timestamp, got %s", v.Tag) 33 } 34 35 timeValue, err := time.Parse(time.RFC3339, v.Value) 36 if err != nil { 37 return fmt.Errorf("unable to parse timestamp: %w", err) 38 } 39 40 *t = Timestamp(timeValue) 41 return nil 42 } 43 44 // IsZero returns true if the timestamp is the zero value. 45 func (t Timestamp) IsZero() bool { 46 return time.Time(t).IsZero() 47 } 48 49 // Before returns true if t is before u. 50 func (t Timestamp) Before(u Timestamp) bool { 51 return time.Time(t).Before(time.Time(u)) 52 } 53 54 // After returns true if t is after u. 55 func (t Timestamp) After(u Timestamp) bool { 56 return time.Time(t).After(time.Time(u)) 57 } 58 59 // String returns the timestamp as an RFC3339 string. 60 func (t Timestamp) String() string { 61 return time.Time(t).UTC().Format(time.RFC3339) 62 } 63 64 // Equal returns true if t and u are equal. 65 func (t Timestamp) Equal(u Timestamp) bool { 66 return time.Time(t).Equal(time.Time(u)) 67 }