Skip to content

proposal: encoding/json/v2: encode time with format:unix as integer instead of float #73486

Open
@lmittmann

Description

@lmittmann

Proposal Details

The new package json/v2 has format options unix, unixmilli, unixmicro, and unixnano for time.Time, that encode the time as float of seconds, milliseconds, microseconds, and nanoseconds since epoch. The encoded float has nanosecond precision for each unit.

I propose that we change the format options unix, unixmilli, unixmicro, and unixnano to emit integer timestamps, rather than floats.

Motivation

Many APIs that use epoch timestamps use integers epoch timestamps. High precision floats are not commonly used due to rounding issues in clients.

The time package has the time.Time-methods Unix, UnixMilli, UnixMicro, and UnixNano that return integer values. Equally named json/v2 format options should have the same logic to avoid confusion.

time.Time json/v2 format
Unix() int64 format:unix
UnixMilli() int64 format:unixmilli
UnixMicro() int64 format:unixmicro
UnixNano() int64 format:unixnano

Example of Current Behavior (Playground)

type times struct {
	Time  time.Time `json:"time,format:unix"`
	Time2 time.Time `json:"time2,format:unixmilli"`
	Time3 time.Time `json:"time3,format:unixmicro"`
	Time4 time.Time `json:"time4,format:unixnano"`
}

enc, _ := json.Marshal(times{
	Time:  time.Unix(123, 456),
	Time2: time.Unix(123, 456),
	Time3: time.Unix(123, 456),
	Time4: time.Unix(123, 456),
})
fmt.Print(string(enc))
// Output:
// {"time":123.000000456,"time2":123000.000456,"time3":123000000.456,"time4":123000000456}

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions