Go-json解析时间格式

需要自己实现 MarshalJSONUnmarshalJSON方法,如果只需要存或者取,实现一个也可

type Date struct {
	time.Time
}

func (d *Date) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%s"`, d.Format("2006-01-02"))), nil
}

func (d *Date) UnmarshalJSON(b []byte) error {
	var err error
	// 指定时区
	d.Time, err = time.ParseInLocation(`"2006-01-02"`, string(b),time.Local)
	if err != nil {
		return err
	}
	return nil
}

type Datetime struct {
	time.Time
}

func (d *Datetime) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("%s", d.Format("2006-01-02 15:04:05"))), nil
}

func (d *Datetime) UnmarshalJSON(b []byte) error {
	var err error
	d.Time, err = time.Parse(`"2006-01-02 15:04:05"`, string(b))
	if err != nil {
		return err
	}
	return nil
}

测试

type Amazing struct {
	D Date `json:"data"`
}

func main() {
	demo := &Amazing{}
	_ = json.Unmarshal([]byte(`{"data":"2021-03-30"}`), demo)
	fmt.Println(demo) // &{2021-03-30 00:00:00 +0800 CST}

	demo2 := &Amazing{D: Date{time.Now()}}
	v, _ := json.Marshal(demo2)
	fmt.Println(string(v)) // {"data":"2021-03-30"}
}

进阶,配合gorm

type Date time.Time

func (d *Date) Scan(value interface{}) (err error) {
	nullTime := &sql.NullTime{}
	err = nullTime.Scan(value)
	*d = Date(nullTime.Time)
	return
}

func (d Date) Value() (driver.Value, error) {
	y, m, dd := time.Time(d).Date()
	// time.Local 本地时区,如果使用 time.time(d).Location() 有可能为空切换到UTC时区
	return time.Date(y, m, dd, 0, 0, 0, 0, time.Local), nil
}

// GormDataType gorm common data type
func (d Date) GormDataType() string {
	return "date"
}

func (d *Date) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%s"`, (*time.Time)(d).Format("2006-01-02"))), nil
}

func (d *Date) UnmarshalJSON(b []byte) error {
	dd, err := time.ParseInLocation(`"2006-01-02"`, string(b), time.Local)
	if err != nil {
		return err
	}
	*d = Date(dd)
	return nil
}

type Datetime time.Time

func (d *Datetime) Scan(value interface{}) (err error) {
	nullTime := &sql.NullTime{}
	err = nullTime.Scan(value)
	*d = Datetime(nullTime.Time)
	return
}

func (d Datetime) Value() (driver.Value, error) {
	y, m, dd := time.Time(d).Date()
	return time.Date(y, m, dd, 0, 0, 0, 0, time.Time(d).Location()), nil
}

func (d *Datetime) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("%s", (*time.Time)(d).Format(`"2006-01-02 15:04:05"`))), nil
}

func (d *Datetime) UnmarshalJSON(b []byte) error {
	dd, err := time.ParseInLocation(`"2006-01-02 15:04:05"`, string(b), time.Local)
	if err != nil {
		return err
	}
	*d = Datetime(dd)
	return nil
}

// GormDataType gorm common data type
func (d Datetime) GormDataType() string {
	return "datetime"
}
posted @ 2021-03-30 15:51  Binb  阅读(607)  评论(0编辑  收藏  举报