创建包含时区的日期字符串

huangapple go评论81阅读模式
英文:

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

huangapple
  • 本文由 发表于 2021年8月5日 22:20:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/68668362.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定