Go: time: time.Unix(0, 0).IsZero() == false

Created on 12 Aug 2019  Â·  6Comments  Â·  Source: golang/go

I'm aware that IsZero is implemented with year 1, Jan 1 being 'zero'. (https://golang.org/pkg/time/#Time.IsZero) However, it causes confusion when most developers use epoch time at 0, and the IsZero function is then false for time.Unix(0,0).

Why is zero time considered year 1, Jan 1 instead of epoch 0?

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

$ go version
go version go1.12.7 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
GOARCH="amd64"
GOBIN="/Users/bex/workspace/bin"
GOCACHE="/Users/bex/Library/Caches/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/bex/workspace/bosh-cli-workspace"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/Cellar/go/1.12.7/libexec"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.12.7/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/z7/dyfnyjn14rngs_4g0bfwc5440000gp/T/go-build443496455=/tmp/go-build -gno-record-gcc-switches -fno-common"

What did you do?

https://play.golang.org/p/NtsWcGMJMaU

What did you expect to see?

IsZero evaluates to true for the beginning of epoch time. I'm unsure what the compelling reason for deviating from typical standards is.

What did you see instead?

Using epoch time within my applications and golang requires special consideration and it does not work as expected. I feel the deviation is unnecessarily complicated, though now would be a breaking change so we cannot just change it now.

FrozenDueToAge

Most helpful comment

add IsUnixZero()?

All 6 comments

This is working as intended and documented:

https://golang.org/pkg/time/#Time
https://golang.org/pkg/time/#Time.IsZero

Even if we wanted to change it, we couldn't at this point for go1compat reasons.

Go's time.Time zero value is not the Unix epoch zero value. The Unix func converts from Unix to Go.

@bradfitz Can fix it on go2

@runner-mei We could change it in a v2 of the time package, but we aren't going to do that. See the discussion at https://golang.org/src/time/time.go?#L346.

var TimeFromUnixZero = time.Unix(0, 0)
t := time.Now()
isZero := t.Equal(TimeFromUnixZero)

I use this instead

add IsUnixZero()?

I don't think this comes up often enough to need a special function or method.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stub42 picture stub42  Â·  3Comments

michaelsafyan picture michaelsafyan  Â·  3Comments

ashb picture ashb  Â·  3Comments

natefinch picture natefinch  Â·  3Comments

mingrammer picture mingrammer  Â·  3Comments