gpt4 book ai didi

go - go语言中的时间转换问题

转载 作者:IT王子 更新时间:2023-10-29 01:25:01 26 4
gpt4 key购买 nike

我正在尝试了解 Go 语言中时间转换的问题。这是代码示例:

package main

import (
"fmt"
"time"
)

func unix2Str(ts int64) string {
const layout = "20060102"
t := time.Unix(ts, 0)
return t.Format(layout)
}

func unixTime(ts string) int64 {
const layout = "20060102"
t, err := time.Parse(layout, ts)
if err != nil {
fmt.Println(err)
return 0
}
return t.Unix()
}
func main() {
ts1 := "20110320"
ts2 := "20110321"

ut1 := unixTime(ts1)
ut2 := unixTime(ts2)

fmt.Println(ts1, ut1, unix2Str(ut1))
fmt.Println(ts2, ut2, unix2Str(ut2))
}

它打印以下输出:

20110320 1300579200 20110319
20110321 1300665600 20110320

但是由于我进行了从字符串格式到 Unix 格式的转换并反向转换,所以我希望字符串格式的日期得到相同的结果。但事实并非如此。事实上,打印的 unix 时间 1300579200 在 python 中转换为我开始使用的原始日期,例如

>>> time.strftime("%Y%m%d", time.gmtime(1300579200))
'20110320'

这是 Go 代码中的错误还是我遗漏了什么?

最佳答案

这是因为您本地的时区和 UTC 之间存在差异。 Parse 返回 UTC 时间,Unix 返回本地时间。例如,

package main

import (
"fmt"
"time"
)

func unix2Str(ts int64) string {
const layout = "20060102"
t := time.Unix(ts, 0)
fmt.Println(t)
return t.Format(layout)
}

func unixTime(ts string) int64 {
const layout = "20060102"
t, err := time.Parse(layout, ts)
if err != nil {
fmt.Println(err)
return 0
}
fmt.Println(t)
return t.Unix()
}

func main() {
ts1 := "20110320"
ts2 := "20110321"

ut1 := unixTime(ts1)
ut2 := unixTime(ts2)

fmt.Println(ts1, ut1, unix2Str(ut1))
fmt.Println(ts2, ut2, unix2Str(ut2))
}

输出:

2011-03-20 00:00:00 +0000 UTC
2011-03-21 00:00:00 +0000 UTC
2011-03-19 20:00:00 -0400 EDT
20110320 1300579200 20110319
2011-03-20 20:00:00 -0400 EDT
20110321 1300665600 20110320

func Parse

func Parse(layout, value string) (Time, error)

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

In the absence of a time zone indicator, Parse returns a time in UTC.


func Unix

func Unix(sec int64, nsec int64) Time

Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC.

关于go - go语言中的时间转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50022088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com