如何使用没有数字偏移量的默认区域格式化日期
How to format date with default zone without the numeric offset
如果我将日期从数据库扫描到包含 time.Time 中的日期的结构,默认情况下它将打印如下:
"2019-11-27T16:38:55+07:00"
有没有办法像这样格式化它,而无需重新解析具有 time.Time 类型的所有内容?
"0001-01-01T00:00:00Z"
我可以手动重新格式化所有内容,但必须有更好的方法。因为我要扫描成一个切片,要重新格式化日期,我必须循环结果才能做到这一点。
有什么建议吗?
可以使用time.Time
的.UTC()方法获取UTC时区的时间值,然后重新格式化成字符串,就可以得到对应的UTC日期。
str1 := "2019-11-27T16:38:55+07:00"
tme1, _ := time.Parse(time.RFC3339, str1)
tme2 := tme1.UTC()
str2 := tme2.Format(time.RFC3339)
fmt.Println("str1", str1) // str1 2019-11-27T16:38:55+07:00
fmt.Println("str2", str2) // str2 2019-11-27T09:38:55Z
工作操场https://play.golang.org/p/7uRKDeRZBUx
This is for an API that will be used by a front end app, that requires it to be formatted like this.
无论是 javascript、go 还是任何其他 programming/scripting 语言,在不同时区解析等效的日期字符串都会得到等效的日期。在 js 中查看下面的示例:
console.log(new Date("2019-11-27T16:38:55+07:00").toString())
// "Wed Nov 27 2019 16:38:55 GMT+0700 (Western Indonesia Time)"
console.log(new Date("2019-11-27T09:38:55Z").toString())
// "Wed Nov 27 2019 16:38:55 GMT+0700 (Western Indonesia Time)"
看到两个日期解析操作在解析并转换为字符串后生成相同的字符串
如果我将日期从数据库扫描到包含 time.Time 中的日期的结构,默认情况下它将打印如下:
"2019-11-27T16:38:55+07:00"
有没有办法像这样格式化它,而无需重新解析具有 time.Time 类型的所有内容?
"0001-01-01T00:00:00Z"
我可以手动重新格式化所有内容,但必须有更好的方法。因为我要扫描成一个切片,要重新格式化日期,我必须循环结果才能做到这一点。
有什么建议吗?
可以使用time.Time
的.UTC()方法获取UTC时区的时间值,然后重新格式化成字符串,就可以得到对应的UTC日期。
str1 := "2019-11-27T16:38:55+07:00"
tme1, _ := time.Parse(time.RFC3339, str1)
tme2 := tme1.UTC()
str2 := tme2.Format(time.RFC3339)
fmt.Println("str1", str1) // str1 2019-11-27T16:38:55+07:00
fmt.Println("str2", str2) // str2 2019-11-27T09:38:55Z
工作操场https://play.golang.org/p/7uRKDeRZBUx
This is for an API that will be used by a front end app, that requires it to be formatted like this.
无论是 javascript、go 还是任何其他 programming/scripting 语言,在不同时区解析等效的日期字符串都会得到等效的日期。在 js 中查看下面的示例:
console.log(new Date("2019-11-27T16:38:55+07:00").toString())
// "Wed Nov 27 2019 16:38:55 GMT+0700 (Western Indonesia Time)"
console.log(new Date("2019-11-27T09:38:55Z").toString())
// "Wed Nov 27 2019 16:38:55 GMT+0700 (Western Indonesia Time)"
看到两个日期解析操作在解析并转换为字符串后生成相同的字符串