about summary refs log tree commit diff
path: root/fun/clbot/gerrit/gerritevents/time.go
blob: 7fbfaa3f5c479f3420baf2560a3f5ca57e9579c9 (plain) (blame)
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
package gerritevents

import (
	"fmt"
	"strconv"
	"time"
)

// Time is a time.Time that is formatted as a Unix timestamp in JSON.
type Time struct {
	time.Time
}

// UnmarshalJSON unmarshals a Unix timestamp into a Time.
func (t *Time) UnmarshalJSON(bs []byte) error {
	if string(bs) == "null" {
		return nil
	}
	u, err := strconv.ParseInt(string(bs), 10, 64)
	if err != nil {
		return err
	}
	t.Time = time.Unix(u, 0)
	return nil
}

// MarshalJSON marshals a Time into a Unix timestamp.
func (t *Time) MarshalJSON() ([]byte, error) {
	if t.IsZero() {
		return []byte("null"), nil
	}
	return []byte(fmt.Sprintf("%d", t.Unix())), nil
}

// IsSet returns true if the time.Time is non-zero.
func (t *Time) IsSet() bool {
	return !t.IsZero()
}