-
Notifications
You must be signed in to change notification settings - Fork 3
/
str_milliseconds.go
44 lines (34 loc) · 931 Bytes
/
str_milliseconds.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
package epoch
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
// StrMilliseconds - same as epoch.Milliseconds, but for strings.
type StrMilliseconds struct {
time.Time
}
// NewStrMilliseconds - returns Milliseconds
func NewStrMilliseconds(t time.Time) StrMilliseconds {
return StrMilliseconds{Time: t}
}
// MarshalJSON - implements JSON marshaling interface
func (m StrMilliseconds) MarshalJSON() ([]byte, error) {
ms := m.Time.UnixNano() / nsPerMs
return json.Marshal(strconv.FormatInt(ms, 10))
}
// UnmarshalJSON - implements JSON unmarshaling interface
func (m *StrMilliseconds) UnmarshalJSON(data []byte) error {
var v string
err := json.Unmarshal(data, &v)
if err != nil {
return fmt.Errorf("failed to unmarshal epoch.StrMilliseconds: %w", err)
}
ms, err := parseInt64(v)
if err != nil {
return fmt.Errorf("failed to parse epoch.StrMilliseconds: %w", err)
}
m.Time = msToTime(ms)
return nil
}