【问题标题】:How to print exact time of time based timezone in go? [closed]如何在go中打印基于时间的时区的确切时间? [关闭]
【发布时间】:2021-05-07 07:00:01
【问题描述】:

您好,这次我想转换 2021-04-13 14:00:00 +0700 WIB

2021-04-13 21:00:00

基本上我需要根据某个时区位置打印准确的时间,我不能使用这种方法

 time.ParseInLocation("02-Jan-2006 15:04:05", someTime.Format("02-Jan-2006 15:04:05"), location)

因为它会返回yy-mm-dd- hh:mm:ss offset timezone

【问题讨论】:

  • 您能否说明一下如何2021-04-13 14:00:00 +0700 WIB 派生2021-04-13 21:00:00? +7 表示 在 UTC 之前,所以我假设 2021-04-13 07:00:00 Z?
  • 要更改时间值的时区,请使用the In method。无需格式化再解析。

标签: go time timezone


【解决方案1】:

如果你仔细观察,你在位置解析得到的时间就是那个位置的时间。这不像2021-04-13 14:00:00 +0700 WIB2021-04-13 21:00:00 但事实上,时间是2021-04-13 14:00:00 在你给定的位置。 +0700 只显示偏移量,您不必使用偏移量更新时间。

func main() {
    now, _ := time.Parse("02-01-2006 15:04:05 -0700", "07-05-2021 12:00:00 +0530")

    loc, _ := time.LoadLocation("UTC")
    fmt.Printf("UTC Time:       %s\n", now.In(loc))

    loc, _ = time.LoadLocation("Europe/Berlin")
    fmt.Printf("Berlin Time:    %s\n", now.In(loc))

    loc, _ = time.LoadLocation("America/New_York")
    fmt.Printf("New York Time:  %s\n", now.In(loc))

    loc, _ = time.LoadLocation("Asia/Kolkata")
    fmt.Printf("India Time:     %s\n", now.In(loc))

    loc, _ = time.LoadLocation("Asia/Singapore")
    fmt.Printf("Singapore Time: %s\n", now.In(loc))
}

上面代码的输出是:

UTC Time:       2021-05-07 06:30:00 +0000 UTC
Berlin Time:    2021-05-07 08:30:00 +0200 CEST
New York Time:  2021-05-07 02:30:00 -0400 EDT
India Time:     2021-05-07 12:00:00 +0530 IST
Singapore Time: 2021-05-07 14:30:00 +0800 +08

每个位置的时间都是指当地的时间。偏移量仅显示与 GMT 的偏移量。

【讨论】:

  • 对于UTC,您可以使用快捷方式now.UTC()
  • 它是time.Now().UTC()
  • 不,我的意思是代码中的变量now ^^(一种误导性变量名称)
  • 是的,可以:D 谢谢
猜你喜欢
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2019-05-23
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
相关资源
最近更新 更多