Golang时间序列化
在Golang中如何正确序列化和反序列化时间类型?我尝试使用json.Marshal处理time.Time类型时,输出的格式不符合预期。请问标准库中有没有推荐的序列化方式?如何自定义时间格式进行序列化?另外,不同时区的时间序列化时需要注意哪些问题?
2 回复
在Golang中,时间序列化常用time.Time类型。使用json.Marshal可将时间转为JSON字符串,默认格式为RFC3339。如需自定义格式,可通过实现MarshalJSON方法或使用time.Format指定布局,如"2006-01-02 15:04:05"。
更多关于Golang时间序列化的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中,时间序列化通常使用time.Time类型与JSON或其他格式相互转换。以下是常见方法:
1. JSON序列化
默认使用RFC3339格式(例如 "2023-10-05T14:30:00Z"):
package main
import (
"encoding/json"
"fmt"
"time"
)
type Event struct {
Timestamp time.Time `json:"timestamp"`
Name string `json:"name"`
}
func main() {
event := Event{
Timestamp: time.Now(),
Name: "Meeting",
}
// 序列化
data, _ := json.Marshal(event)
fmt.Println(string(data)) // {"timestamp":"2023-10-05T14:30:00Z","name":"Meeting"}
// 反序列化
var newEvent Event
json.Unmarshal(data, &newEvent)
fmt.Println(newEvent.Timestamp) // 2023-10-05 14:30:00 +0000 UTC
}
2. 自定义时间格式
使用time.Layout或自定义格式:
type CustomEvent struct {
Timestamp time.Time `json:"timestamp"`
}
// 自定义JSON序列化
func (c *CustomEvent) MarshalJSON() ([]byte, error) {
return []byte(`{"timestamp":"` + c.Timestamp.Format("2006-01-02 15:04:05") + `"}`), nil
}
// 自定义JSON反序列化
func (c *CustomEvent) UnmarshalJSON(data []byte) error {
// 实现解析逻辑(略)
return nil
}
3. 使用字符串标签指定格式
type Event struct {
Timestamp string `json:"timestamp"` // 存储为字符串
}
// 手动处理时间
func NewEvent(t time.Time) Event {
return Event{
Timestamp: t.Format("2006-01-02 15:04:05"),
}
}
关键点:
- 默认使用RFC3339格式
- 自定义格式需实现
MarshalJSON/UnmarshalJSON - 时间模板必须使用Go参考时间:
Mon Jan 2 15:04:05 MST 2006
选择方案根据具体需求决定,一般推荐使用默认RFC3339以保证兼容性。

