Reputation: 45491
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
Upvotes: 0
Views: 719
Reputation: 417757
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.
Upvotes: 6
Reputation: 45491
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)
}
Upvotes: 3