go json返回时间字符串处理time.Time类型

参考博客 :golang 时间出现 -62135596800 问题(解决方案)golang 时间出现 -62135596800 问题(解决方案)
Golang json转换时间格式问题Golang json转换时间格式问题
go 实际开发中 time.Time类型 提供是字符串, 而很多场景中需要对请求的接口再次处理,将go json化后的字符串转成time.Time类型
go程序 将时间转换成json 时 会默认把时间转换为RFC3339 格式

2018-01-14T21:45:54+08:00

先来看看time包中对格式的常量定义

const (
    ANSIC       = "Mon Jan _2 15:04:05 2006"
    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    RFC822      = "02 Jan 06 15:04 MST"
    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    RFC3339     = "2006-01-02T15:04:05Z07:00"
    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    Kitchen     = "3:04PM"
    // Handy time stamps.
    Stamp      = "Jan _2 15:04:05"
    StampMilli = "Jan _2 15:04:05.000"
    StampMicro = "Jan _2 15:04:05.000000"
    StampNano  = "Jan _2 15:04:05.000000000"
)

切入正题
怎么样把这个时间

2018-01-14T21:45:54+08:00

转换为

2018-01-14 21:45:54

其实琢磨了一下方法还是很简单

str:="2018-01-14T21:45:54+08:00"
//先将时间转换为字符串

tt,_:=time.Parse("2006-01-02T15:04:05Z07:00",str)

//格式化时间
fmt.Println(tt.Format("2006-01-02 15:04:05"))

就可以得到自己想要的时间了

time.Parse()的layout参数 就是上面常量定义的 RFC3339
如果其他格式 也只要复制对应的layout 就可以了

tt.Format()

是将时间按照 自定义的方式 进行个格式化
这里的 2006-01-02 15:04:05 一定不能变

原文地址:https://www.cnblogs.com/liuqun/p/13622290.html