github.com/MontFerret/ferret@v0.18.0/pkg/runtime/values/date_time.go (about) 1 package values 2 3 import ( 4 "hash/fnv" 5 "time" 6 7 "github.com/wI2L/jettison" 8 9 "github.com/MontFerret/ferret/pkg/runtime/core" 10 "github.com/MontFerret/ferret/pkg/runtime/values/types" 11 ) 12 13 const DefaultTimeLayout = time.RFC3339 14 15 type DateTime struct { 16 time.Time 17 } 18 19 var ZeroDateTime = DateTime{ 20 time.Time{}, 21 } 22 23 func NewCurrentDateTime() DateTime { 24 return DateTime{time.Now()} 25 } 26 27 func NewDateTime(time time.Time) DateTime { 28 return DateTime{time} 29 } 30 31 func ParseDateTime(input interface{}) (DateTime, error) { 32 return ParseDateTimeWith(input, DefaultTimeLayout) 33 } 34 35 func ParseDateTimeWith(input interface{}, layout string) (DateTime, error) { 36 switch value := input.(type) { 37 case string: 38 t, err := time.Parse(layout, value) 39 40 if err != nil { 41 return DateTime{time.Now()}, err 42 } 43 44 return DateTime{t}, nil 45 default: 46 return DateTime{time.Now()}, core.ErrInvalidType 47 } 48 } 49 50 func MustParseDateTime(input interface{}) DateTime { 51 dt, err := ParseDateTime(input) 52 53 if err != nil { 54 panic(err) 55 } 56 57 return dt 58 } 59 60 func (t DateTime) MarshalJSON() ([]byte, error) { 61 return jettison.MarshalOpts(t.Time, jettison.NoHTMLEscaping()) 62 } 63 64 func (t DateTime) Type() core.Type { 65 return types.DateTime 66 } 67 68 func (t DateTime) String() string { 69 return t.Time.String() 70 } 71 72 func (t DateTime) Compare(other core.Value) int64 { 73 if other.Type() == types.DateTime { 74 other := other.(DateTime) 75 76 if t.After(other.Time) { 77 return 1 78 } 79 80 if t.Before(other.Time) { 81 return -1 82 } 83 84 return 0 85 } 86 87 return types.Compare(types.DateTime, other.Type()) 88 } 89 90 func (t DateTime) Unwrap() interface{} { 91 return t.Time 92 } 93 94 func (t DateTime) Hash() uint64 { 95 h := fnv.New64a() 96 97 h.Write([]byte(t.Type().String())) 98 h.Write([]byte(":")) 99 100 bytes, err := t.Time.GobEncode() 101 102 if err != nil { 103 return 0 104 } 105 106 h.Write(bytes) 107 108 return h.Sum64() 109 } 110 111 func (t DateTime) Copy() core.Value { 112 return NewDateTime(t.Time) 113 }