-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathtime.go
81 lines (68 loc) · 1.88 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
// Copyright (c) 2020, Peter Ohler, All rights reserved.
package gen
import (
"fmt"
"strconv"
"strings"
"time"
)
// TimeFormat defines how time is encoded. Options are to use a time. layout
// string format such as time.RFC3339Nano, "second" for a decimal
// representation, "nano" for a an integer.
var TimeFormat = ""
// TimeWrap if not empty encoded time as an object with a single member. For
// example if set to "@" then and TimeFormat is RFC3339Nano then the encoded
// time will look like '{"@":"2020-04-12T16:34:04.123456789Z"}'
var TimeWrap = ""
// Time is a time.Time Node.
type Time time.Time
// String returns a string representation of the Node.
func (n Time) String() string {
var b strings.Builder
n.buildString(&b)
return b.String()
}
// Alter returns the backing time.Time value of the Node.
func (n Time) Alter() any {
return time.Time(n)
}
// Simplify returns the backing time.Time value of the Node.
func (n Time) Simplify() any {
return time.Time(n)
}
// Dup returns the backing time.Time value of the Node.
func (n Time) Dup() Node {
return n
}
// Empty returns false.
func (n Time) Empty() bool {
return false
}
func (n Time) buildString(b *strings.Builder) {
if 0 < len(TimeWrap) {
b.WriteString(`{"`)
b.WriteString(TimeWrap)
b.WriteString(`":`)
}
switch TimeFormat {
case "", "nano":
b.WriteString(strconv.FormatInt(time.Time(n).UnixNano(), 10))
case "second":
// Decimal format but float is not accurate enough so build the output
// in two parts.
nano := time.Time(n).UnixNano()
secs := nano / int64(time.Second)
if 0 < nano {
_, _ = fmt.Fprintf(b, "%d.%09d", secs, nano-(secs*int64(time.Second)))
} else {
_, _ = fmt.Fprintf(b, "%d.%09d", secs, -nano+(secs*int64(time.Second)))
}
default:
b.WriteString(`"`)
b.WriteString(time.Time(n).Format(TimeFormat))
b.WriteString(`"`)
}
if 0 < len(TimeWrap) {
b.WriteString("}")
}
}