日期转换代码在不同的机器上表现不同

时间:2020-10-24 09:17:54

标签: linux docker date go

我有以下代码:

package main

import (
    "fmt"
    "time"
)

func main() {
    loc := "Jan 06"
    date := "2020-12-31 16:00:00 +0000 UTC"
    layout := "2006-01-02 15:04:05 -0700 MST"
    t, err := time.Parse(layout, date)
    if err != nil {
        fmt.Print("Error")
    }

    fmt.Println(t)
    GetFormattedDate(t, loc)
}

func GetFormattedDate(date time.Time, layout string) (string, error) {
    
    fmt.Println("\n\n====================================================")
    fmt.Println("time.Now(): ", time.Now())
    fmt.Println("time.Now().Location(): ", time.Now().Location())
    fmt.Println("Converting: ", date)
    configLocale := "Singapore"
    fmt.Println("configLocale: ", configLocale)

    loc, err := time.LoadLocation(configLocale)
    fmt.Println("loc: ", loc)
    if err != nil {
        return "", err
    }

    date = date.In(loc)
    fmt.Println("date.In(loc): ", date)
    fmt.Println("layout: ", layout)
    converted := fmt.Sprintf(date.Format(layout))
    fmt.Println("converted fmt: ", converted)
    fmt.Println("\n\n==================================================")
    return fmt.Sprintf(date.Format(layout)), nil
}

在本地运行时,我得到:

====================================================
time.Now():  2009-11-10 23:00:00 +0000 UTC m=+0.000000001
time.Now().Location():  Local
Converting:  2020-12-31 16:00:00 +0000 UTC
configLocale:  Singapore
loc:  Singapore
date.In(loc):  2021-01-01 00:00:00 +0800 +08 // This is the issue
layout:  Jan 06
converted fmt:  Jan 21


==================================================

但是当我在linux box服务器上运行相同的代码时,我得到:

time.Now(): 2020-10-24 09:04:22.256288497 +0000 UTC m=+252.011109438
time.Now().Location(): UTC
Converting: 2020-12-31 16:00:00 +0000 UTC
msg":"configLocale: Singapore
msg":"loc: Singapore
date.In(loc): 2020-12-31 16:00:00 +0000 +0000 // This is the issue
layout: Jan 06
converted fmt: Dec 20

我要做什么:

我正在尝试将2020-12-31 16:00:00 +0000 UTC转换为特定于语言环境的日期,语言环境为Singapore。我的布局是Jan 06

对于一台计算机,此日期将转换为Dec 20,对于另一台计算机,此日期将转换为Jan 21

特别是当我深入研究时,我感觉方法date = date.In(loc)在不同的机器上返回了不同的结果,尽管将位置设置为Singapore并显式地传递了它,如日志所示。

Playground

但是在服务器命令行上:

/ # zdump Singapore 
Singapore  Mon Oct 26 02:10:18 2020 +08

关于如何解决此问题的任何建议?

1 个答案:

答案 0 :(得分:3)

它是configLocale的值。它必须是IANA Time Zone,“”,“ UTC”或“ Local”。 “ Singapore”在列表中,但是它是不遵循Continent/Region的标准格式的极少数之一。这是一种不寻常的格式,因此在服务器计算机上的查找将使查找失败,因此默认为UTC(不返回错误,这可能是错误),并且由于新加坡提前8个小时,因此最终要花费8个小时。如果您将“亚洲/新加坡”用于configLocale,它将起作用。