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

Use*_*er3 5 linux date go docker

我有以下代码:

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
}
Run Code Online (Sandbox Code Playgroud)

当我在本地运行它时,我得到:

====================================================
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


==================================================
Run Code Online (Sandbox Code Playgroud)

但是当我在我的 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
Run Code Online (Sandbox Code Playgroud)

我正在尝试做的事情:

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

对于一台机器,这个日期会转换为,Dec 20而对于另一台机器,它会转换为Jan 21

具体来说,当我深入挖掘时,date = date.In(loc)尽管设置了 locationSingapore并明确传递了它,但我觉得该方法在不同的机器上返回不同的结果,如日志中所示。

操场

但是在服务器命令行上:

/ # zdump Singapore 
Singapore  Mon Oct 26 02:10:18 2020 +08
Run Code Online (Sandbox Code Playgroud)

任何建议我如何解决这个问题?

Sea*_*n F 3

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