go-discord-bot / util / time_parser / time_parser.go
time_parser.go
Raw
package time_parser

import (
	"log"
	"os"
	"strconv"
	"time"
)

type Time time.Time

var (
	ErrLogger = log.New(os.Stdout, "[ PARSER ]\t", log.Ldate|log.Ltime)
)

func (t Time) MarshalJSON() ([]byte, error) {
	return []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil
}

func (t *Time) UnmarshalJSON(b []byte) error {
	r := string(b)
	q, err := strconv.ParseInt(r, 10, 64)
	if err != nil {
		return err
	}

	// Cast unix timestamp to human readable time.Time
	// NOTE: Riot's API returns Unix Timestamps in Milliseconds
	offset, err := time.ParseDuration("-08.00h")
	*(*time.Time)(t) = time.UnixMilli(q).Add(offset)
	return nil
}

// Unix returns t as a Unix time, the number of seconds elapsed since Jan 1, 1970 UTC.
// The result does not depend on the location associated with t.
func (t Time) Unix() int64 {
	return time.Time(t).Unix()
}

// Time returns the JSON time as a time.Time instance in UTC
func (t Time) Time() time.Time {
	return time.Time(t).UTC()
}

// String returns t as a formatted string
func (t Time) String() string {
	return t.Time().String()
}