Go time.Now().UnixNano() convert to milliseconds?

huangapple go评论94阅读模式
英文:

Go time.Now().UnixNano() convert to milliseconds?

问题

你可以使用time.Now().UnixNano()函数获取当前时间的Unix时间戳,然后将其转换为毫秒。以下是修改后的函数:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / int64(time.Millisecond)
}

这样,你将得到以毫秒为单位的Unix时间戳。

英文:

How can I get Unix time in Go in milliseconds?

I have the following function:

func makeTimestamp() int64 {
	return time.Now().UnixNano() % 1e6 / 1e3
}

I need less precision and only want milliseconds.

答案1

得分: 217

2021年的答案:

截至go v1.17,time包添加了UnixMicro()UnixMilli()函数,因此正确的答案是:time.Now().UnixMilli()

对于go v.1.16及更早版本:

只需进行除法运算:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / 1e6
}

1e6,即1,000,000,是一毫秒中的纳秒数。

以下是一个可以编译和运行以查看输出的示例:

package main

import (
    "time"
    "fmt"
)

func main() {
    a := makeTimestamp()

    fmt.Printf("%d \n", a)
}

func makeTimestamp() int64 {
    return time.Now().UnixNano() / 1e6
}
英文:

The 2021 answer:

As of go v1.17, the time package added UnixMicro() and UnixMilli(), so the correct answer would be: time.Now().UnixMilli()

For go v.1.16 and earlier:

Just divide it:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / 1e6
}

1e6, i.e. 1 000 000, is the number of nanoseconds in a millisecond.

Here is an example that you can compile and run to see the output

package main

import (
	"time"
	"fmt"
)

func main() {
	a := makeTimestamp()

	fmt.Printf("%d \n", a)
}

func makeTimestamp() int64 {
    return time.Now().UnixNano() / 1e6
}

答案2

得分: 69

保持简单。

func NowAsUnixMilli() int64 {
    return time.Now().UnixNano() / 1e6
}
英文:

Keep it simple.

func NowAsUnixMilli() int64 {
    return time.Now().UnixNano() / 1e6
}

答案3

得分: 68

如@Jono在@OneOfOne的回答中指出的那样,正确的答案应该考虑到纳秒的持续时间。例如:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

OneOfOne的答案之所以有效,是因为time.Nanosecond恰好是1,除以1没有任何影响。我对Go语言了解不够,不知道这种情况在将来是否会改变,但对于严格正确的答案,我会使用这个函数,而不是OneOfOne的答案。我怀疑这不会有任何性能劣势,因为编译器应该能够很好地优化这个函数。

参考:https://en.wikipedia.org/wiki/Dimensional_analysis

从另一个角度来看,time.Now().UnixNano()time.Millisecond都使用相同的单位(纳秒)。只要这是真的,OneOfOne的答案应该完全有效。

英文:

As @Jono points out in @OneOfOne's answer, the correct answer should take into account the duration of a nanosecond. Eg:

func makeTimestamp() int64 {
    return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

OneOfOne's answer works because time.Nanosecond happens to be 1, and dividing by 1 has no effect. I don't know enough about go to know how likely this is to change in the future, but for the strictly correct answer I would use this function, not OneOfOne's answer. I doubt there is any performance disadvantage as the compiler should be able to optimize this perfectly well.

See https://en.wikipedia.org/wiki/Dimensional_analysis

Another way of looking at this is that both time.Now().UnixNano() and time.Millisecond use the same units (Nanoseconds). As long as that is true, OneOfOne's answer should work perfectly well.

答案4

得分: 12

在Go语言中,你可以使用Time.UnixMilli方法来获取以毫秒为单位的Unix时间。从Go 1.17版本开始,不再需要进行纳秒级的除法运算。以下是一个示例代码:

// 一个确定的日期值
t := time.Date(2021, 7, 16, 0, 0, 0, 0, time.UTC)

m := t.UnixMilli()
fmt.Println(m) // 1626393600000

你可以在Playground上运行这段代码:https://play.golang.org/p/JSExv5jw2ZW

英文:

> How can I get Unix time in Go in milliseconds?

Go 1.17 and above

No more divisions from nanoseconds. Starting from Go 1.17 you can just use Time.UnixMilli method directly:

// a deterministic date value
t := time.Date(2021, 7, 16, 0, 0, 0, 0, time.UTC)

m := t.UnixMilli()
fmt.Println(m) // 1626393600000

Playground: https://play.golang.org/p/JSExv5jw2ZW

答案5

得分: 5

在https://github.com/golang/go/issues/44196中,randall77建议使用以下代码:

time.Now().Sub(time.Unix(0,0)).Milliseconds()

这利用了Go语言中time.Duration已经具有Milliseconds方法的特性。

英文:

At https://github.com/golang/go/issues/44196 randall77 suggested

time.Now().Sub(time.Unix(0,0)).Milliseconds()

which exploits the fact that Go's time.Duration already have Milliseconds method.

答案6

得分: 3

我认为在除法之前将时间四舍五入到毫秒会更好。

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

这是一个示例程序:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(unixMilli(time.Unix(0, 123400000)))
    fmt.Println(unixMilli(time.Unix(0, 123500000)))
    m := makeTimestampMilli()
    fmt.Println(m)
    fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
    return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
    return unixMilli(time.Now())
}

上述程序在我的机器上打印了以下结果:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST
英文:

I think it's better to round the time to milliseconds before the division.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Here is an example program:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

The above program printed the result below on my machine:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST

答案7

得分: 2

简单但准确的解决方案如下:

func nowAsUnixMilliseconds() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / 1e6
}

这个函数实现了以下功能:

  1. 将时间值正确地四舍五入到最近的毫秒(与整数除法相比:它只丢弃结果值的小数部分);
  2. 不涉及Go特定的时间间隔强制转换,因为它使用了一个表示绝对毫秒/纳秒分割的数值常量。

附注:我已经运行了使用常量和复合分割器的基准测试,结果几乎没有差异,所以可以放心使用更易读或更符合语言规范的解决方案。

英文:

Simple-read but precise solution would be:

func nowAsUnixMilliseconds(){
    return time.Now().Round(time.Millisecond).UnixNano() / 1e6
}

This function:

  1. Correctly rounds the value to the nearest millisecond (compare with integer division: it just discards decimal part of the resulting value);
  2. Does not dive into Go-specifics of time.Duration coercion — since it uses a numerical constant that represents absolute millisecond/nanosecond divider.

P.S. I've run benchmarks with constant and composite dividers, they showed almost no difference, so feel free to use more readable or more language-strict solution.

huangapple
  • 本文由 发表于 2014年6月9日 22:49:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/24122821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定