0

Go has methods to extract almost every component of a timestamp, eg time.Second(), time.Nano(), but none to extract the millisecond portion of a timestamp.

How does one extract the millisecond value of a timestamp.

eg, in the case of a timestamp like:

2021-01-07 10:33:06.511

i want to extract 511

2
  • @mkopriva better to use time.Millisecond constant value insted of 1000_000. It is more explicit Jan 7, 2021 at 18:39
  • 1
    Updated version as per @DanielHornik's comment: play.golang.org/p/ambNkD_apB2
    – mkopriva
    Jan 7, 2021 at 18:42

2 Answers 2

6

To access the fraction seconds, you may use time.Nanosecond(). And if we convert it to time.Duration (time.Duration is exactly the nanoseconds count), we can take advantage of its Duration.Milliseconds() method (which of course does no magic but code will be clearer and easier to read):

func extractMs(t time.Time) int64 {
    return time.Duration(t.Nanosecond()).Milliseconds()
}

Try it on the Go Playground.

3

there is an answer in the comments, but i want to post here to be cannonical:

func extractMillisecond(t time.Time) int {
    ms := time.Duration(t.Nanosecond()) / time.Millisecond
    return int(ms)
}
1
  • You can shorten this to: return t.Nanosecond() / int64(time.Millisecond), and eliminate one type conversion. Jan 7, 2021 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.