在开发过程中,我们有时会遇到这样的问题,将 2020-11-08t08:18:46+08:00 转成 2020-11-08 08:18:46,怎么解决这个问题?
解决这个问题,最好不要用字符串截取,或者说字符串截取是最笨的方法,这应该是时间格式化的问题。

我们先看一下 golang time 包中支持的 format 格式:

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"
)

我们找到了 rfc3339 ,那就很简单了,我们封装一个方法 rfc3339tocstlayout,见下面代码。

package timeutil

import "time"

var (
 cst *time.location
)

// cstlayout china standard time layout
const cstlayout = "2006-01-02 15:04:05"

func init() {
 var err error
 if cst, err = time.loadlocation("asia/shanghai"); err != nil {
 panic(err)
 }
}

// rfc3339tocstlayout convert rfc3339 value to china standard time layout
func rfc3339tocstlayout(value string) (string, error) {
 ts, err := time.parse(time.rfc3339, value)
 if err != nil {
 return "", err
 }

 return ts.in(cst).format(cstlayout), nil
}

运行一下

rfc3339str := "2020-11-08t08:18:46+08:00"
cst, err := timeutil.rfc3339tocstlayout(rfc3339str)
if err != nil {
 fmt.println(err)
}
fmt.println(cst)

输出:
2020-11-08 08:18:46

小结

同理,若遇到 rfc3339nano、rfc822、rfc1123 等格式,也可以使用类似的方法,只需要在 time.parse() 中指定时间格式即可。

到此这篇关于go中time.rfc3339 时间格式化的实现的文章就介绍到这了,更多相关go time.rfc3339 时间格式化内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!