如何使用特定时区解析时间

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

How to parse time using a specific timezone

问题

我正在使用函数time.ParseTime()和布局"2006-01-02 15:04"来从字符串中获取一个时间结构体。

当我使用任何有效的时间字符串执行该函数时,我得到一个指向该时间戳的时间结构体,但它是以UTC格式表示的。

我该如何将它转换为不同的时区?明确一点,我想要相同的时间戳,但是使用不同的时区。我不想在时区之间进行转换;我只想获取相同的时间对象,但不是以UTC格式表示。

英文:

I am to get a time struct from a string. I am using the function time.ParseTime() with the layout "2006-01-02 15:04".

When I execute the function with any valid time string I get a time struct pointing to that time stamp but it is in UTC.

How can I change it to a different time zone? To be clear I want the same timestamp but with a different time zone. I don't want to convert between timezones; I just want to get the same time object but not in UTC.

答案1

得分: 9

使用time.ParseInLocation函数来解析没有给定时区的时间。time.Local表示本地时区,将其作为Location参数传入。

package main

import (
	"fmt"
	"time"
)

func main() {
	// 这将遵循给定的时区。
	// 2012-07-09 05:02:00 +0000 CEST
	const formWithZone = "Jan 2, 2006 at 3:04pm (MST)"
	t, _ := time.ParseInLocation(formWithZone, "Jul 9, 2012 at 5:02am (CEST)", time.Local)
	fmt.Println(t)

	// 没有指定时区,将使用本地时区。
	// 我的时区是PDT:2012-07-09 05:02:00 -0700 PDT
	const formWithoutZone = "Jan 2, 2006 at 3:04pm"
	t, _ = time.ParseInLocation(formWithoutZone, "Jul 9, 2012 at 5:02am", time.Local)
	fmt.Println(t)
}

以上是给定的代码示例,使用time.ParseInLocation函数解析时间。

英文:

Use time.ParseInLocation to parse time in a given Location when there's no time zone given. time.Local is your local time zone, pass that in as your Location.

package main

import (
	"fmt"
	"time"
)

func main() {
	// This will honor the given time zone.
    // 2012-07-09 05:02:00 +0000 CEST
	const formWithZone = "Jan 2, 2006 at 3:04pm (MST)"
	t, _ := time.ParseInLocation(formWithZone, "Jul 9, 2012 at 5:02am (CEST)", time.Local)
	fmt.Println(t)

	// Lacking a time zone, it will use your local time zone.
    // Mine is PDT: 2012-07-09 05:02:00 -0700 PDT
    const formWithoutZone = "Jan 2, 2006 at 3:04pm"
	t, _ = time.ParseInLocation(formWithoutZone, "Jul 9, 2012 at 5:02am", time.Local)
	fmt.Println(t)
}

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

发表评论

匿名网友

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

确定