Golang Check If Time Is Empty Example

From the Go Tour basics you may already have stumbled upon the concept of zero values in Go. Check out this section of the Go Tour https://tour.golang.org/basics/12. We can see how the zero value for Go variables is defined.

Variables declared without an explicit initial value are given their zero value.

Golang Zero Values

The zero value for numeric types is 0, for stirngs is "" (empty string) and for boolean types is false. For time.Time the zero value is 0001-01-01 00:00:00 +0000 UTC. You can try this out in by looking at the following snippet of code.

package main

import (
    "fmt"
    "time"
)

func main() {
    var t time.Time
    fmt.Printf("%v", t)
}

You will see the expected output as follows

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

You can try this code on the Go playground https://play.golang.org/p/bOrt6cQpA0I

How do we check if a date/time is empty?

We can use a method exported directly from within the time package itself. The IsZero method returns whether a time has the zero value or not

func (t Time) IsZero() bool

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

Let’s see an example on how this can be used to quickly see if the time/date is zero/empty.

package main

import (
    "fmt"
    "time"
)

func main() {
    var t time.Time
    fmt.Printf("%v %v\n\n", t, t.IsZero())
    t = time.Now()
    fmt.Printf("%v %v", t, t.IsZero())
}

The expected output is as follows

0001-01-01 00:00:00 +0000 UTC true
2009-11-10 23:00:00 +0000 UTC m=+0.000000001 false

You can also try this out on the Go Playground https://play.golang.org/p/VZeuUqKPbIe

Join the Golang Developers Community on Golang Cafe