TransWikia.com

Why is the user defined time's location nil

Stack Overflow Asked by Kelly Flet on December 23, 2021

I’m using go 1.13 and I have a user defined type of type time.Time, and when creating that value with a given location of UTC, the loc attribute is still nil (having a nil loc causes panics in certain time functions, so this is not acceptable). Playground here.

type CustomTime time.Time

func main() {
    t := CustomTime(time.Date(2020, time.July, 23, 1, 0, 0, 0, time.UTC))
    fmt.Printf("%+v",t) // prints {wall:0 ext:63731062800 loc:<nil>}
}

FYI: background info, I’m using this custom time to implement Scan() for my database handler, and when I compare a custom time value defined above (with nil location to the value from the db (non-nil location), my tests are failing due to the comparison failing. Any help or pointers in the right direction would be greatly appreciated.

One Answer

If you look at the doc, time.Time is of type

type Time struct {
    //...
    wall uint64
    ext  int64
    
    // loc specifies the Location that should be used to
    // determine the minute, hour, month, day, and year
    // that correspond to this Time.
    // The nil location means UTC.
    // All UTC times are represented with loc==nil, never loc==&utcLoc.
    loc *Location
}

nil loc actually means UTC. You can verify the same by printing the equality

fmt.Println(time.UTC == time.Time(t).Location())

// Output: true

You see a nil when you print t because you are literally printing the struct Time without using its default Stringer as you have wrapped it with a Custom Type i.e. CustomTime. Hence the loc field will be nil.

fmt.Printf("%+v", time.Time(t))
// This will print UTC for the location.

If you want to use CustomTime everywhere, instead of creating a type alias you can embed time.Time in a struct so that CustomTime can behave like time.Time

type CustomTime struct {
    time.Time
}

func main() {
    t := CustomTime{time.Date(2020, time.July, 23, 1, 0, 0, 0, time.UTC)}
    fmt.Printf("%+v", t) // Prints: 2020-07-23 01:00:00 +0000 UTC
}

Answered by poWar on December 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP