如何使用正确的分钟格式化 Go 中的本地时间对象?

How to format a local time object in Go with correct minutes?

编辑:我用代码更新了问题,强调了为什么所谓的重复解决方案对我不起作用

我正在尝试采用 UTC (+0000) 时间并将它们格式化为本地时间(在我的例子中是东部时间),而不对任何时区偏移进行硬编码(以避免实施夏令时校正)。

我有以下代码演示了我遇到的问题

package main

import (
    "fmt"
    "time"
)

func main() {
    // Here I load the timezone
    timezone, _ := time.LoadLocation("America/New_York")

    // I parse the time
    t, _ := time.Parse("Mon Jan 2 15:04:05 +0000 2006", "Tue Jul 07 10:38:18 +0000 2015")

    // This looks correct, it's still a utc time
    fmt.Println(t)
    // 2015-07-07 10:38:18 +0000 UTC

    // This seems to be fine - -4 hours to convert to est
    t = t.In(timezone)
    fmt.Println(t)
    // 2015-07-07 06:38:18 -0400 EDT

    // This prints 6:07am, completely incorrect as it should be 6:38am
    fmt.Println(t.Format("Monday Jan 2, 3:01pm"))
    // Tuesday Jul 7, 6:07am
}

(https://play.golang.org/p/e57slFhWFk)

所以对我来说,它似乎可以很好地解析和转换时区,但是当我使用格式输出时,它摆脱了分钟并使用 07。我将分钟设置为什么并不重要,它总是结果为 07.

您的布局(格式)字符串不正确。正如 time 包的文档中所述,此时布局字符串必须表示:

Mon Jan 2 15:04:05 MST 2006

解析时,使用如下格式字符串:

t, _ := time.Parse("Mon Jan 02 15:04:05 -0700 2006", "Tue Jul 07 10:38:18 +0000 2015")

并且在打印时,使用这种格式字符串:

fmt.Println(t.Format("Monday Jan 2, 3:04pm"))

这将产生您预期的输出:

Tuesday Jul 7, 6:38am

Go Playground 上试用。