237

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
  • 29,163
  • 13
  • 53
  • 59
  • 52
    And you can use `IsZero()` to detect the zero time. – Matt Apr 15 '14 at 04:34
  • 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

3 Answers3

401

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
  • 18,419
  • 19
  • 55
  • 71
gextra
  • 7,843
  • 8
  • 35
  • 59
  • 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
  • 25
    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
245

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
  • 24,967
  • 7
  • 63
  • 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
6

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

dethtron5000
  • 9,721
  • 1
  • 29
  • 32