MelonBlog

golang日期类型自动格式化

go的time.Time默认的序列化格式一般很难用到业务中来,每次都要调用Format方法来转换挺麻烦的,项目中可以将time.Time包装一下,实现自定义的UnmarshalJSONMarshalJSON方法,这样就可以达到自动格式化的目的。

实现

自定义Time类型

package model
import "time"
const (
	DateFormat     = "2006-01-02"
	TimeFormat     = "15:04:05"
	DateTimeFormat = "2006-01-02 15:04:05"
)
type Time struct {
	time.Time
	pattern string
}
func Now() Time {
	return Time{
		Time:    time.Now(),
		pattern: DateTimeFormat,
	}
}
func (t *Time) SetPattern(pattern string) {
	t.pattern = pattern
}
func (t *Time) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+t.pattern+`"`, string(data), time.Local)
	*t = Time{
		Time:    now,
		pattern: t.pattern,
	}
	return
}
func (t Time) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(t.pattern)+2)
	b = append(b, '"')
	b = t.Time.AppendFormat(b, t.pattern)
	b = append(b, '"')
	return b, nil
}
func (t Time) String() string {
	return t.Time.Format(t.pattern)
}

测试

package model
import (
	"testing"
	"time"
)
func TestTime(t *testing.T) {
	uft := time.Now()
	t.Logf("uft: %v", uft)
	ft := Now()
	t.Logf("ft: %v", ft)
	ft.SetPattern(DateFormat)
	t.Logf("ft: %v", ft)
	ft.SetPattern(TimeFormat)
	t.Logf("ft: %v", ft)
}

输出

=== RUN   TestTime
    time_test.go:10: uft: 2024-01-15 18:25:43.497689 +0800 CST m=+0.000794334
    time_test.go:12: ft: 2024-01-15 18:25:43
    time_test.go:14: ft: 2024-01-15
    time_test.go:16: ft: 18:25:43
--- PASS: TestTime (0.00s)
PASS

友情链接


Copyright © 2023 www.tiangua.info 鄂ICP备2022015834号