Mingyu
Mingyu

Reputation: 33399

What is the `zero` value for time.Time in Go?

In an error condition, I tried to return nil, which throws the error:

cannot use nil as type time.Time in return argument

What is the zero value for time.Time?

Upvotes: 291

Views: 274033

Answers (4)

Oscar Gallardo
Oscar Gallardo

Reputation: 2728

Tested on Go v1.18

The default value for time.Time is:

0001-01-01 00:00:00 +0000 UTC

Checking with IsZero() function is a clean way.

var zeroTime time.Time

if zeroTime.IsZero() {
    // do something when zero
}

Upvotes: 6

gextra
gextra

Reputation: 8913

You should use the Time.IsZero() function instead:

func (Time) IsZero

or

func (t Time) IsZero() bool

IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

Upvotes: 459

zeantsoi
zeantsoi

Reputation: 26203

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:

fmt.Println(time.Time{})

The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

Upvotes: 304

dethtron5000
dethtron5000

Reputation: 10841

The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC See http://play.golang.org/p/vTidOlmb9P

Upvotes: 9

Related Questions