DEV Community

Steve Coffman
Steve Coffman

Posted on

1 2

When Now is not the time (in Go)

#go

When testing two time.Time variables for equality in Go, you may find that there are (ahem) times when you get surprising results if you don't use time.Equal():

package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()
    nowUTC := now.UTC()

    fmt.Println("now:   ", now.Location(), now.Format("15:04"))
    fmt.Println("nowUTC:", nowUTC.Location(), " ", nowUTC.Format("15:04"))
    fmt.Println("-----")

    fmt.Printf("now == nowUTC:     %t\n", now == nowUTC)

    fmt.Printf("now.Equal(nowUTC): %t\n", now.Equal(nowUTC))

}

// Output:
// now:    Local 23:00
// nowUTC: UTC   23:00
// -----
// now == nowUTC:     false
// now.Equal(nowUTC): true

Run it in the Go Playground!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay