【问题标题】:IST time zone error in time package go golang时间包go golang中的IST时区错误
【发布时间】:2019-06-24 12:12:04
【问题描述】:

我需要将 RFC3339 格式的任何给定时区转换为 RFC3339 格式的系统时间。但是对于像 IST 这样的少数时区,它会抛出错误并且时间仍然是 UTC。 对于转换哪个功能服务更好? time.parse 或 time.In.

我尝试将 UTC 转换为 IST,但失败了。

package main

import (
    "fmt"
    "time"
)

func main() {

    //now time
    now := time.Now()
    fmt.Println("now ", now)
    zone, _ := now.Zone()
    fmt.Println("zone->", zone)

    ll, llerr := time.LoadLocation(zone)
    fmt.Println("Load Location", ll, llerr)
    // Convert the given time to system based time zone
    t, err := time.ParseInLocation(time.RFC3339, "2017-04-25T23:03:00Z", ll)
    fmt.Println("t - parsein", t)
    fmt.Println("err - parsein", err)
    //fmt.Println("t2 - parse", t.In(ll))

}

错误:unknown time zone IST

预期:需要将任何时区转换为系统时区。

【问题讨论】:

标签: go time


【解决方案1】:

您无法使用该名称加载印度 IST 时区,因为名称“IST”不明确。这可能意味着印度、爱尔兰、以色列等时区,它们有不同的时区偏移和规则。详情见Why is time.Parse not using the timezone?

如果 IST 是您的本地时区,time.Local 变量将表示该时区。如果您有time.Time,您可以使用Time.In()“切换”到另一个区域,Time.Local() 也会返回您本地区域的时间。

当然,这段代码在另一个区域运行时会“中断”。为了确保它在所有地方的行为都相同,请像这样显式加载印度 IST 区域:

loc, err := time.LoadLocation("Asia/Kolkata")
if err != nil {
    panic(err)
}

fmt.Println(time.Now())
fmt.Println(time.Now().In(loc))

Go Playground 上会输出:

2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009-11-11 04:30:00 +0530 IST

【讨论】:

  • 好的,但我们仍然不知道哪些位置时区有同样的问题。因为必须在许多地方执行相同的代码,如果我们遇到相同的问题怎么办。为了避免这种情况,我计划从 time.Zone() 本身开始,但它又没有帮助。上述解决方案解决了 IST 问题,因为我们知道确切的术语。所以我们需要它在系统时间本身的帮助下找出来。所以任何方式都可以这样做。
  • @kish 我不明白你的意思。
猜你喜欢
  • 2013-07-08
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2021-12-12
  • 2019-04-04
  • 2014-05-11
相关资源
最近更新 更多