英文:
Creating date string with inclusion of time zone
问题
我尝试了几种方法来从time.Now()生成2021-08-06T16:00:00+0200
格式的字符串,其中尾部的+0200表示时区(在这个例子中是CET时区),包括以下方法,但它没有正确地附加时间差。
func createDateString(time time.Time) string {
if time.IsZero() {
return ""
}
return time.UTC().Format("2006-01-02T15:04:05Z")
}
如何在不单独获取时区然后拼接的情况下,高效地生成类似于2021-08-06T16:00:00+0200
的当前时间字符串?
英文:
I tried a couple of ways to generate 2021-08-06T16:00:00+0200
string from time.Now(), where trailing +0200 indicates the timezone (in this example CET time zone), including the following method, but it was not attaching the time difference correctly.
func createDateString(time time.Time) string {
if time.IsZero() {
return ""
}
return time.UTC().Format("2006-01-02T15:04:05Z")
}
How can I efficiently generate 2021-08-06T16:00:00+0200
-like string from current time, without obtaining time zone separately and then concatenating it.
答案1
得分: 3
根据mkopriva的建议,使用-700
代替Z
,并移除.UTC()
:
package main
import (
"fmt"
"time"
)
func main() {
loc := time.FixedZone("CET", 2*60*60)
now := time.Now().In(loc)
fmt.Println(createDateString(now))
}
func createDateString(time time.Time) string {
if time.IsZero() {
return ""
}
return time.Format("2006-01-02T15:04:05-0700")
}
输出结果:
2009-11-11T01:00:00+0200
英文:
Based on the suggestion of mkopriva using -700
instead of Z
and removing .UTC()
:
package main
import (
"fmt"
"time"
)
func main() {
loc := time.FixedZone("CET", 2*60*60)
now := time.Now().In(loc)
fmt.Println(createDateString(now))
}
func createDateString(time time.Time) string {
if time.IsZero() {
return ""
}
return time.Format("2006-01-02T15:04:05-0700")
}
Output:
2009-11-11T01:00:00+0200
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论