1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/values/date_time.go

112 lines
1.8 KiB
Go
Raw Normal View History

2018-09-18 22:42:38 +02:00
package values
import (
2018-10-05 21:17:22 +02:00
"hash/fnv"
2018-09-18 22:42:38 +02:00
"time"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values/types"
2018-09-18 22:42:38 +02:00
)
2018-11-01 01:26:36 +02:00
const DefaultTimeLayout = time.RFC3339
2018-09-18 22:42:38 +02:00
type DateTime struct {
time.Time
}
2018-10-07 07:07:44 +02:00
var ZeroDateTime = DateTime{
time.Time{},
}
2018-10-05 21:17:22 +02:00
func NewCurrentDateTime() DateTime {
return DateTime{time.Now()}
}
2018-09-18 22:42:38 +02:00
func NewDateTime(time time.Time) DateTime {
return DateTime{time}
}
func ParseDateTime(input interface{}) (DateTime, error) {
2018-11-01 01:26:36 +02:00
return ParseDateTimeWith(input, DefaultTimeLayout)
2018-09-18 22:42:38 +02:00
}
func ParseDateTimeWith(input interface{}, layout string) (DateTime, error) {
switch value := input.(type) {
2018-09-18 22:42:38 +02:00
case string:
t, err := time.Parse(layout, value)
2018-09-18 22:42:38 +02:00
if err != nil {
return DateTime{time.Now()}, err
}
return DateTime{t}, nil
default:
return DateTime{time.Now()}, core.ErrInvalidType
}
}
func MustParseDateTime(input interface{}) DateTime {
2018-09-18 22:42:38 +02:00
dt, err := ParseDateTime(input)
if err != nil {
panic(err)
}
return dt
}
func (t DateTime) MarshalJSON() ([]byte, error) {
return t.Time.MarshalJSON()
}
func (t DateTime) Type() core.Type {
return types.DateTime
2018-09-18 22:42:38 +02:00
}
func (t DateTime) String() string {
return t.Time.String()
}
func (t DateTime) Compare(other core.Value) int64 {
if other.Type() == types.DateTime {
2018-09-18 22:42:38 +02:00
other := other.(DateTime)
if t.After(other.Time) {
return 1
}
if t.Before(other.Time) {
return -1
}
return 0
}
return types.Compare(types.DateTime, other.Type())
2018-09-18 22:42:38 +02:00
}
func (t DateTime) Unwrap() interface{} {
return t.Time
}
2018-10-05 21:17:22 +02:00
func (t DateTime) Hash() uint64 {
h := fnv.New64a()
2018-09-18 22:42:38 +02:00
2018-10-05 21:17:22 +02:00
h.Write([]byte(t.Type().String()))
h.Write([]byte(":"))
2018-09-18 22:42:38 +02:00
2018-10-05 21:17:22 +02:00
bytes, err := t.Time.GobEncode()
2018-09-18 22:42:38 +02:00
if err != nil {
return 0
}
2018-10-05 21:17:22 +02:00
h.Write(bytes)
return h.Sum64()
2018-09-18 22:42:38 +02:00
}
2018-09-27 17:53:26 +02:00
func (t DateTime) Copy() core.Value {
2018-09-27 17:53:26 +02:00
return NewDateTime(t.Time)
}