-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.go
More file actions
92 lines (74 loc) · 1.67 KB
/
time.go
File metadata and controls
92 lines (74 loc) · 1.67 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
86
87
88
89
90
91
92
package objects
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"time"
)
var _ json.Marshaler = (*Time)(nil)
var _ json.Unmarshaler = (*Time)(nil)
var _ Mentionable = (*Time)(nil)
type TimestampStyle string
const (
StyleShortTime TimestampStyle = "t"
StyleLongTime TimestampStyle = "T"
StyleShortDate TimestampStyle = "d"
StyleLongDate TimestampStyle = "D"
StyleShortDateTime TimestampStyle = "f"
StyleLongDateTime TimestampStyle = "F"
StyleRelative TimestampStyle = "R"
)
func NewTime(t time.Time) *Time {
return &Time{t}
}
type Time struct {
time.Time
}
func (t *Time) MarshalJSON() ([]byte, error) {
if t.IsZero() {
return []byte(`""`), nil
}
return []byte(strconv.Quote(t.Time.Format(time.RFC3339))), nil
}
func (t *Time) UnmarshalJSON(b []byte) error {
if bytes.Equal(b, []byte(`""`)) {
return nil
}
var ts time.Time
if err := json.Unmarshal(b, &ts); err != nil {
return err
}
t.Time = ts
return nil
}
func (t *Time) Format(style TimestampStyle) string {
return fmt.Sprintf("<t:%d:%s>", t.Unix(), style)
}
func (t *Time) String() string {
return t.ShortDateTime()
}
func (t *Time) Mention() string {
return t.LongDateTime()
}
func (t *Time) ShortTime() string {
return t.Format(StyleShortTime)
}
func (t *Time) LongTime() string {
return t.Format(StyleLongTime)
}
func (t *Time) ShortDate() string {
return t.Format(StyleShortDate)
}
func (t *Time) LongDate() string {
return t.Format(StyleLongDate)
}
func (t *Time) ShortDateTime() string {
return t.Format(StyleShortDateTime)
}
func (t *Time) LongDateTime() string {
return t.Format(StyleLongDateTime)
}
func (t *Time) Relative() string {
return t.Format(StyleRelative)
}