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