-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatetime.go
More file actions
74 lines (64 loc) · 1.41 KB
/
datetime.go
File metadata and controls
74 lines (64 loc) · 1.41 KB
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
package zed
import (
"github.com/ogen-go/ogen"
"time"
)
var _ Schema[time.Time] = (*DateTimeSchema)(nil)
const (
EpochNanosecond EpochUnit = 1 << iota
EpochMicrosecond
EpochMillisecond
EpochSecond
)
type (
DateTimeSchema struct {
*baseSchema[string, time.Time]
epochUnit EpochUnit
layout string
}
EpochUnit uint8
)
func newDateTimeSchema(err string) *DateTimeSchema {
return &DateTimeSchema{
baseSchema: newBaseSchema[string, time.Time](err),
layout: time.RFC3339,
}
}
func (s *DateTimeSchema) EpochUnit(interval EpochUnit) *DateTimeSchema {
s.epochUnit = interval
return s
}
func (s *DateTimeSchema) Layout(layout string) *DateTimeSchema {
s.layout = layout
return s
}
func (s *DateTimeSchema) Validate(v any, _ SchemaValidationFlag) (out time.Time, e error) {
switch val := v.(type) {
case string:
out, e = time.Parse(s.layout, val)
case float64:
switch s.epochUnit {
case EpochNanosecond:
out = time.Unix(0, int64(val))
case EpochMicrosecond:
out = time.UnixMicro(int64(val))
case EpochMillisecond:
out = time.UnixMilli(int64(val))
case EpochSecond:
out = time.Unix(int64(val), 0)
default:
e = s.err
}
case time.Time:
out = val
default:
e = s.err
}
return
}
func (s *DateTimeSchema) ValidateGeneric(v any, flags SchemaValidationFlag) (any, error) {
return s.Validate(v, flags)
}
func (s *DateTimeSchema) ToSchema() *ogen.Schema {
return ogen.DateTime()
}