1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-19 13:22:54 +00:00
arikawa/discord/time.go

118 lines
2 KiB
Go
Raw Normal View History

2020-01-02 05:39:52 +00:00
package discord
import (
"encoding/json"
2020-01-17 22:29:13 +00:00
"strings"
2020-01-02 05:39:52 +00:00
"time"
)
// Timestamp has a valid zero-value, which can be checked using the Valid()
// method. This is useful for optional timestamps such as EditedTimestamp.
2020-01-02 05:39:52 +00:00
type Timestamp time.Time
const TimestampFormat = time.RFC3339 // same as ISO8601
var (
_ json.Unmarshaler = (*Timestamp)(nil)
_ json.Marshaler = (*Timestamp)(nil)
)
2020-01-26 09:06:54 +00:00
func NewTimestamp(t time.Time) Timestamp {
return Timestamp(t)
}
func NowTimestamp() Timestamp {
return NewTimestamp(time.Now())
}
2020-01-02 05:39:52 +00:00
func (t *Timestamp) UnmarshalJSON(v []byte) error {
2020-01-17 22:29:13 +00:00
str := strings.Trim(string(v), `"`)
if str == "null" {
return nil
}
r, err := time.Parse(TimestampFormat, str)
2020-01-02 05:39:52 +00:00
if err != nil {
return err
}
*t = Timestamp(r)
return nil
}
func (t Timestamp) MarshalJSON() ([]byte, error) {
2020-01-21 01:06:51 +00:00
if !t.Valid() {
2020-01-19 06:06:00 +00:00
return []byte("null"), nil
}
2020-01-21 01:06:51 +00:00
return []byte(`"` + t.Format(TimestampFormat) + `"`), nil
2020-01-02 05:39:52 +00:00
}
func (t Timestamp) Valid() bool {
2020-01-21 01:06:51 +00:00
return !t.Time().IsZero()
}
func (t Timestamp) Format(fmt string) string {
return t.Time().Format(fmt)
}
func (t Timestamp) Time() time.Time {
return time.Time(t)
}
2020-01-15 04:43:34 +00:00
//
type UnixTimestamp int64
func (t UnixTimestamp) String() string {
return t.Time().String()
}
func (t UnixTimestamp) Time() time.Time {
return time.Unix(int64(t), 0)
}
//
type UnixMsTimestamp int64
func (t UnixMsTimestamp) String() string {
return t.Time().String()
}
func (t UnixMsTimestamp) Time() time.Time {
return time.Unix(0, int64(t)*int64(time.Millisecond))
}
//
type Seconds int
func DurationToSeconds(dura time.Duration) Seconds {
return Seconds(dura.Seconds())
}
func (s Seconds) String() string {
return s.Duration().String()
}
func (s Seconds) Duration() time.Duration {
return time.Duration(s) * time.Second
}
2020-01-15 04:43:34 +00:00
//
type Milliseconds int
func DurationToMilliseconds(dura time.Duration) Milliseconds {
return Milliseconds(dura.Milliseconds())
}
func (ms Milliseconds) String() string {
return ms.Duration().String()
}
func (ms Milliseconds) Duration() time.Duration {
return time.Duration(ms) * time.Millisecond
}