Check If a Date/Time Has Been Set with IsZero

· 198 words · 1 minute read

In Go, we can store and use dates using the time package and although a date in Go cannot be saved as null (because there’s no such thing) there is an unset state. This unset state can be shown as 0001-01-01 00:00:00 +0000 UTC and there’s a simple way we can check if a date variable has been populated, as demonstrated below. It’s also important to note that these are not unix timestamps, which go back as far as 1970, but can handle a large spectrum of dates.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
    "fmt"
    "time"
)

func main() {

    var myDate time.Time

    // IsZero returns a bool of whether a date has been set, but as the printf shows it will
    // still print a zero-based date if it hasn't been set.
    if myDate.IsZero() {
        fmt.Printf("No date has been set, %s\n", myDate)
    }

    // Demonstrating that by setting a date, IsZero now returns false
    myDate = time.Date(2019, time.February, 1, 0, 0, 0, 0, time.UTC)
    if !myDate.IsZero() {
        fmt.Printf("A date has been set, %s\n", myDate)
    }
}

check is date set or not

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!