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

问题描述:

Edit: I have updated the question with code that highlights why the alleged duplicate's solution doesn't work for me

I am trying to take UTC (+0000) times and format them into local times (eastern time in my case) without hard coding any timezone offsets (as to avoid implementing dst correction).

I have the following code which demonstrates the problem I am having

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)

So to me it seems that it parses and converts timezones fine, but when I output it using format, it gets rid of the minutes and uses 07. It doesn't matter what I set the minutes to, it always comes out as 07.

编辑:我用代码突出显示了问题,该代码突出显示了为什么所谓的重复项解决方案对我不起作用 p>

我正在尝试采用UTC(+0000)时间并将其格式化为本地时间(在我的情况下为东部时间),而不用硬编码任何时区偏移量(以免实施dst校正)。 p>

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

 包main 
 
import(
“ fmt” 
“  time“ 
)
 
func main(){
 //在这里加载时区
时区,_:= time.LoadLocation(” America / New_York“)
 
 //我解析时间\  nt,_:= time.Parse(“星期一1月2日15:04:05 +0000 2006”,“星期二7月7日10:38:18 +0000 2015”)
 
 //看起来正确,仍然是 utc time 
 fmt.Println(t)
 // 2015年7月7日10:38:18 +0000 UTC 
 
 //这似乎很好--4个小时可以转换为est 
t = t  .In(时区)
 fmt.Println(t)
 // 2015-07-07 06:38:18 -0400 EDT 
 
 //此 打印上午6:07,完全不正确,因为应该是上午6:38 
 fmt.Println(t.Format(“星期一1月2日,下午3:01 pm”))
 // 7月7日,星期二,上午6:07 
} \  n  code>  pre> 
 
 

https://play.golang。 org / p / e57slFhWFk ) p>

所以对我来说,它似乎可以很好地解析和转换时区,但是当我使用格式输出时,它摆脱了分钟并使用了 07.设置分钟数无关紧要,它总是显示为07。 p> div>

Your layout (format) strings are incorrect. As noted in the doc of the time package, the layout string must denote this time:

Mon Jan 2 15:04:05 MST 2006

When parsing, use the following format string:

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

And when printing, use this format string:

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

This will result in your expected output:

Tuesday Jul 7, 6:38am

Try it on the Go Playground.