unix_time.go 1.1 KB
package jtime

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

type UnixTimeSecond time.Time

// MarshalJSON implements json.Marshaler.
func (t UnixTimeSecond) MarshalJSON() ([]byte, error) {
	stamp := fmt.Sprintf("%d", time.Time(t).Unix())
	return []byte(stamp), nil
}

// MarshalJSON implements json.Unmarshaler.
func (t UnixTimeSecond) UnmarshalJSON(v []byte) error {
	str := string(v)
	number, err := strconv.Atoi(str)
	if err != nil {
		return fmt.Errorf("时间类型需要使用时间戳传参:%w", err)
	}
	t = UnixTimeSecond(time.Unix(int64(number), 0))
	return nil
}

type TimeToUnixMsec int64

// MarshalJSON implements json.Marshaler.
func (t TimeToUnixMsec) MarshalJSON() ([]byte, error) {
	stamp := fmt.Sprintf("%d", t)
	return []byte(stamp), nil
}

// MarshalJSON implements json.Unmarshaler.
func (t *TimeToUnixMsec) UnmarshalJSON(v []byte) error {
	if len(v) < 2 {
		*t = 0
		return nil
	}
	str := string(v[1 : len(v)-1])
	number, err := time.Parse(time.RFC3339, str)
	if err != nil {
		return fmt.Errorf("时间类型需要使用时间戳传参:%w", err)
	}
	*t = TimeToUnixMsec(number.Unix() * 1000)
	return nil
}