Skip to content

time: JSON marshaling/unmarshaling does not work reliably for zero Time value #57040

@ShawnHsiung

Description

@ShawnHsiung

What version of Go are you using (go version)?

$ go version go1.18.5 darwin/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/xxx/Library/Caches/go-build"
GOENV="/Users/xxx/Library/Application Support/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE="git.xxx.cn"
GOMODCACHE="/Users/xxx/Workspace/golib-common/pkg/mod"
GONOPROXY="git.xxx.cn"
GONOSUMDB="git.xxx.cn"
GOOS="darwin"
GOPATH="/Users/xxx/Workspace/golib-common"
GOPRIVATE="git.xxx.cn"
GOPROXY="https://goproxy.cn,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GOVCS=""
GOVERSION="go1.18.5"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/xxx/Workspace/xxx/src/git.xxx.cn/xxx/go.mod"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/mh/05pw0l8d64s30wl_hl55bbc40000gn/T/go-build4224931359=/tmp/go-build -gno-record-gcc-switches -fno-common"

What did you do?

https://go.dev/play/p/Xsu1BBKI26i

package main

import (
	"fmt"
	"time"
)

func main() {

	loc, _ := time.LoadLocation("Asia/Shanghai")
	time.Local = loc
	tlocal := time.Time{}.Local()

        fmt.Println("----- Before MarshalJSON -----")
	fmt.Println(tlocal)
	fmt.Println(tlocal.Zone())
	fmt.Println(tlocal.IsZero())

	mal, _ := tlocal.MarshalJSON()
	recv := time.Time{}
	recv.UnmarshalJSON(mal)

	fmt.Println("----- After UnmarshalJSON -----")
	fmt.Println(recv)
	fmt.Println(recv.Zone())
	fmt.Println(recv.IsZero())
}

What did you expect to see?

----- Before MarshalJSON -----
0001-01-01 08:05:43 +0805 LMT
LMT 29143
true
----- After UnmarshalJSON -----
0001-01-01 08:05:43 +0805 +0805
29143 // should be 29143
true // IsZero() should return true

What did you see instead?

----- Before MarshalJSON -----
0001-01-01 08:05:43 +0805 LMT
LMT 29143
true
----- After UnmarshalJSON -----
0001-01-01 08:05:43 +0805 +0805
29100 // lost 43 seconds
false // then IsZero() == false

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions