Skip to content

time: add Time.GoString method to help %#v [freeze exception] #39034

@kevinburke1

Description

@kevinburke1

I have an array of time.Time objects that I retrieved from the database, and I would like to place them in a Go source file. As I understand it, there's not an easy way to do this without a helper method.

  • fmt.Sprintf("%#v\n", t) prints out something like:

    time.Time{wall:0x0, ext:63724924180, loc:(*time.Location)(nil)}

    which not only makes it difficult to determine what time is represented - I can't do math on 63724924180 in my head to determine whether this is yesterday or today, but also can't be embedded directly in a Go program because wall and ext and loc are private variables.

  • I could use t.Format(time.RFC3339) on each item to get an array of strings, but then these need to be re-Parse'd to get a time.Time back, with appropriate error handling.

It could be nice to have either a (time.Time) GoString() string method or a GoString format constant which would print out a format that could be embedded in a Go source file.

For example

fmt.Sprintf(t.Format(time.GoString))

could yield

"time.Date(2020, time.February, 31, 23, 59, 59, 0, nil)"

or similar. I am not sure whether having time.Time implement the GoStringer interface - and change the format printed by %#v - would violate the Go compatibility promise, though I doubt the current wall, ext, loc format is very useful for most people.

The trickiest part of this would be printing Location, which could be implemented by printing out the pointer address for non-nil, non-UTC, non-Local locations - it's no worse than what's currently done.

I suppose we'd also lose some data about the monotonic-ness of the time measurement in question but if you're trying to put this in source code you likely don't care about that bit.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions