dongqi6486 2019-06-05 07:40
浏览 686

golang time.Format()对于相同的unix时间戳给出不同的结果

time.Time initialized with time.Unix() and time.Parse() with exactly the same unix timestamp gives different results being printed with time.Format("2006-01-02")

The problem is not reproducible in playground, but I get it if I compile it myself.

My default time zone is Los Angeles, probably in different timezone result would be different.

go version go version go1.12.1 darwin/amd64

go build

./test

test.go:

package main

import (
    "fmt"
    "time"
)

func main() {
    control1 := time.Unix(1546300800, 0)
    test, _ := time.Parse("2006-01-02", "2019-01-01")

    fmt.Println("control:", control1.Unix(), control1.Format("2006-01-02"))
    fmt.Println("test:", test.Unix(), test.Format("2006-01-02"))
}

./test control: 1546300800 2018-12-31 test: 1546300800 2019-01-01

So unix ts is the same (1546300800), but dates are different. Why?

  • 写回答

1条回答 默认 最新

  • dongliang1941 2019-06-05 07:50
    关注

    The printed dates are different because they have different timezones.

    time.Unix() returns the local Time, while time.Parse():

    Elements omitted from the value are assumed to be zero or, when zero is impossible, one, so parsing "3:04pm" returns the time corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is 0, this time is before the zero Time).

    time.Parse() returns a time.Time having UTC zone by default (if zone info is not part of the input and layout).

    This also explains why you can't see it on the Go Playground: the local time there is UTC.

    Printing the zone info in my local computer (CET timezone):

    fmt.Println("control:", control1.Unix(), control1.Format("2006-01-02 -0700"))
    fmt.Println("test   :", test.Unix(), test.Format("2006-01-02 -0700"))
    
    fmt.Println(control1.Zone())
    fmt.Println(test.Zone())
    

    Outputs:

    control: 1546300800 2019-01-01 +0100
    test   : 1546300800 2019-01-01 +0000
    CET 3600
    UTC 0
    

    If you switch both times to the same zone (e.g. UTC or local), the printed dates will be the same:

    control1 = control1.UTC()
    test = test.UTC()
    

    After this, the output:

    control: 1546300800 2019-01-01 +0000
    test   : 1546300800 2019-01-01 +0000
    UTC 0
    UTC 0
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂