-
Notifications
You must be signed in to change notification settings - Fork 14
/
time.go
106 lines (81 loc) · 2.38 KB
/
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
package transform
import (
"fmt"
"time"
iconfig "github.com/brexhq/substation/internal/config"
"github.com/brexhq/substation/internal/errors"
)
const (
timeDefaultFmt = "2006-01-02T15:04:05.000Z"
)
type timeUnixConfig struct {
Object iconfig.Object `json:"object"`
}
func (c *timeUnixConfig) Decode(in interface{}) error {
return iconfig.Decode(in, c)
}
func (c *timeUnixConfig) Validate() error {
if c.Object.SourceKey == "" && c.Object.TargetKey != "" {
return fmt.Errorf("object_source_key: %v", errors.ErrMissingRequiredOption)
}
if c.Object.SourceKey != "" && c.Object.TargetKey == "" {
return fmt.Errorf("object_target_key: %v", errors.ErrMissingRequiredOption)
}
return nil
}
type timePatternConfig struct {
Object iconfig.Object `json:"object"`
Format string `json:"format"`
Location string `json:"location"`
}
func (c *timePatternConfig) Decode(in interface{}) error {
return iconfig.Decode(in, c)
}
func (c *timePatternConfig) Validate() error {
if c.Object.SourceKey == "" && c.Object.TargetKey != "" {
return fmt.Errorf("object_source_key: %v", errors.ErrMissingRequiredOption)
}
if c.Object.SourceKey != "" && c.Object.TargetKey == "" {
return fmt.Errorf("object_target_key: %v", errors.ErrMissingRequiredOption)
}
if c.Format == "" {
return fmt.Errorf("format: %v", errors.ErrMissingRequiredOption)
}
return nil
}
func timeUnixToBytes(t time.Time) []byte {
return []byte(fmt.Sprintf("%d", t.UnixNano()))
}
// timeUnixToStr converts a UnixNano timestamp to a string.
func timeUnixToStr(ts int64, timeFmt string, loc string) (string, error) {
timeDate := time.Unix(0, ts)
if loc != "" {
ll, err := time.LoadLocation(loc)
if err != nil {
return "", fmt.Errorf("location %s: %v", loc, err)
}
timeDate = timeDate.In(ll)
}
return timeDate.Format(timeFmt), nil
}
func timeStrToUnix(timeStr, timeFmt string, loc string) (time.Time, error) {
var timeDate time.Time
if loc != "" {
ll, err := time.LoadLocation(loc)
if err != nil {
return timeDate, fmt.Errorf("location %s: %v", loc, err)
}
pil, err := time.ParseInLocation(timeFmt, timeStr, ll)
if err != nil {
return timeDate, fmt.Errorf("format %s location %s: %v", timeFmt, loc, err)
}
timeDate = pil
} else {
p, err := time.Parse(timeFmt, timeStr)
if err != nil {
return timeDate, fmt.Errorf("format %s: %v", timeFmt, err)
}
timeDate = p
}
return timeDate, nil
}