在golang中将时间戳转换为ISO格式

Convert timestamp to ISO format in golang

我正在尝试将时间戳 2018-12-17T15:03:49.000+0000 转换为 golang 中的 ISO 格式,但出现错误 cannot parse "+0000" as "Z07:00"

这是我试过的

ts, err := time.Parse(time.RFC3339, currentTime)

有什么想法吗?

这个怎么样?

ts, err := time.Parse("2006-01-02T15:04:05.000+0000", currentTime)

因为时间.RFC3339 只是 2006-01-02T15:04:05Z07:00

注意,前面的答案很长

(tl;dr) 使用:

ts, err := time.Parse("2006-01-02T15:04:05-0700", currentTime)
ts.Format(time.RFC3339)

我真的很喜欢 go 文档,你应该这样做:)

全部来自https://golang.org/pkg/time/#pkg-constants

RFC3339 = "2006-01-02T15:04:05Z07:00"

Some valid layouts are invalid time values for time.Parse, due to formats such as _ for space padding and Z for zone information

这意味着您无法使用布局 Z07:00.

解析 +0000

还有:

The reference time used in the layouts is the specific time:

Mon Jan 2 15:04:05 MST 2006

which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as

01/02 03:04:05PM '06 -0700

您可以按如下方式解析数字时区偏移量格式:

-0700  ±hhmm
-07:00 ±hh:mm
-07    ±hh

或将格式中的符号替换为 Z:

Z0700  Z or ±hhmm
Z07:00 Z or ±hh:mm
Z07    Z or ±hh

分数:

来自这个例子https://play.golang.org/p/V9ubSN6gTdG

// If the fraction in the layout is 9s, trailing zeros are dropped.

do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")

所以你可以这样解析它:

ts, err := time.Parse("2006-01-02T15:04:05.999-0700", currentTime)

此外,来自文档

A decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. When parsing (only), the input may contain a fractional second field immediately after the seconds field, even if the layout does not signify its presence. In that case a decimal point followed by a maximal series of digits is parsed as a fractional second.

这意味着您可以从布局中省略小数点,它会正确解析

ts, err := time.Parse("2006-01-02T15:04:05-0700", currentTime)

要获得 UTC 的时间,只需写 ts.UTC()

要将其格式化为 RFC3339,您可以使用

ts.Format(time.RFC3339)

例子

currentTime := "2018-12-17T17:02:04.123+0530"
ts, err := time.Parse("2006-01-02T15:04:05-0700", currentTime)
if err != nil {
    panic(err)
}

fmt.Println("ts:        ", ts)
fmt.Println("ts in utc: ", ts.UTC())
fmt.Println("RFC3339:   ", ts.Format(time.RFC3339))


// output
// ts:         2018-12-17 17:02:04.123 +0530 +0530
// ts in utc:  2018-12-17 11:32:04.123 +0000 UTC
// RFC3339:    2018-12-17T17:02:04+05:30

操场:https://play.golang.org/p/vfERDm_YINb