oklog/ulid

Convenience method to convert unix time to time.Time?

Closed this issue · 8 comments

The package exposes a Timestamp(...) convenience function to convert from time.Time to a UNIX time in a uint64 but no method to go the other way. Was it a deliberate decision not to include this and, if so, would you mind explaining the rationale?

Thanks again for this awesome package!

I have just found the Unix(uint64) function in the time package which I guess answers my questions.

I wonder if I could make a documentation-only pull request pointing developers to this from the ulid.Time() method?

Something of the form "To convert from a UNIX time to a ULID timestamp, use..." would be nice indeed!

I got some additional learning from having to do this. You have to:

  • truncate from uint64 (returned by ULID.Time()) to int64 (accepted by time.Unix(...))
  • divide by 1000 to go from milliseconds to seconds
  • decide what to pass to the other argument of time.Unix(...)

How would the package maintainers feel about a convenience method to do all of that after all?

So, this?

// Xxx converts a UNIX time in milliseconds, like the value returned
// by the ULID Time method, to a time.Time. Precision is truncated
// at the millisecond.
func Xxx(ms uint64) time.Time {
    s := int64(ms/1e3)
    ns := int64((ms%1e3) * 1e6)
    return time.Unix(s, ns)
}

That would be great! A method bound to ULID would probably be even more useful although the natural name for that is occupied. Naming this isn't easy either though; there's no really obvious complement of Timestamp(...). Sorry for bringing more problems than solutions.

May I open a PR for this?

Yes, please open a PR. I'll leave final approval to @tsenart, he has better taste in API design than I do :)

Thank you!