-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.go
More file actions
85 lines (73 loc) · 2.02 KB
/
Copy pathtime.go
File metadata and controls
85 lines (73 loc) · 2.02 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
75
76
77
78
79
80
81
82
83
84
85
package opt
import (
"encoding/json"
"fmt"
"time"
)
// Time is a nullable time.Time with RFC3339 JSON marshaling.
type Time struct {
Option[time.Time]
}
// NewTime creates a Time with the given value and validity.
func NewTime(t time.Time, valid bool) Time {
return Time{New(t, valid)}
}
// TimeFrom creates a Time that is always valid.
func TimeFrom(t time.Time) Time {
return Time{From(t)}
}
// TimeFromPtr creates a Time from a pointer. Nil results in null.
func TimeFromPtr(t *time.Time) Time {
return Time{FromPtr(t)}
}
// TimeOrNull creates a valid Time if t is non-zero, null otherwise.
func TimeOrNull(t time.Time) Time {
return NewTime(t, !t.IsZero())
}
// Equal reports whether two Times represent the same instant (timezone-independent).
func (t Time) Equal(other Time) bool {
return t.Valid == other.Valid && (!t.Valid || t.V.Equal(other.V))
}
// ExactEqual reports whether two Times are exactly equal (including timezone).
func (t Time) ExactEqual(other Time) bool {
return t.Valid == other.Valid && (!t.Valid || t.V == other.V) //nolint:staticcheck // intentional struct comparison to distinguish timezone
}
// MarshalJSON implements json.Marshaler.
func (t Time) MarshalJSON() ([]byte, error) {
if !t.Valid {
return jsonNull, nil
}
return t.V.MarshalJSON()
}
// UnmarshalJSON implements json.Unmarshaler.
func (t *Time) UnmarshalJSON(data []byte) error {
if len(data) > 0 && data[0] == 'n' {
t.Valid = false
return nil
}
if err := json.Unmarshal(data, &t.V); err != nil {
return fmt.Errorf("opt: couldn't unmarshal JSON: %w", err)
}
t.Valid = true
return nil
}
// MarshalText implements encoding.TextMarshaler.
func (t Time) MarshalText() ([]byte, error) {
if !t.Valid {
return []byte{}, nil
}
return t.V.MarshalText()
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (t *Time) UnmarshalText(text []byte) error {
str := string(text)
if str == "" || str == strNull {
t.Valid = false
return nil
}
if err := t.V.UnmarshalText(text); err != nil {
return err
}
t.Valid = true
return nil
}