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?

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