267

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?

Mingyu
  • 31,751
  • 14
  • 55
  • 60
  • 55
    And you can use `IsZero()` to detect the zero time. – Matt Apr 15 '14 at 04:34
  • 1
    Usually, when I want to return `nil` to make evidence no value has been set, I use pointers as return values in function signature. – bio Nov 23 '20 at 14:49

4 Answers4

436

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
gextra
  • 8,439
  • 8
  • 40
  • 62
  • 1
    Indeed, if comparing whether the given value for time is nil or not, this is what should actually be used. – Gaurav Ojha Feb 02 '17 at 08:03
  • 38
    While this is correct answer for comparison, the OP did not ask about comparison, but rather how to initialize zero value. Accepted answer is correct. – mikijov Apr 07 '19 at 19:16
287

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.

zeantsoi
  • 25,857
  • 7
  • 69
  • 61
  • 10
    "Passing no arguments" makes it sound like a function call. It's a struct literal with no fields specified. X{} is the zero value of the struct X for any X. – Russ Cox Apr 16 '14 at 02:00
  • 1
    @RussCox I don't think that's true. In my case, I have a field of time.Time in my struct which has 'omitempty' attribute. If I don't set that value, it gets automatically set to 0001-01-01 00:00:00 +0000 UTC instead of being ignored. – Gaurav Ojha Sep 14 '16 at 12:20
  • 1
    @GauravOjha See [Golang JSON omitempty With time.Time Field](http://stackoverflow.com/questions/32643815/golang-json-omitempty-with-time-time-field/32646035#32646035). – icza Jan 28 '17 at 03:52
  • Marty! We have to go back! – qciccoretti May 12 '23 at 21:24
7

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

dethtron5000
  • 10,363
  • 1
  • 31
  • 32
3

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
}

Oscar Gallardo
  • 2,240
  • 3
  • 27
  • 47