自从Golang纳秒时间戳以来的时间

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

Time since golang nanosecond timestamp

问题

Q1. 如何从纳秒时间戳创建一个 Golang 的 time 结构体?

Q2. 然后如何计算自此时间戳以来的小时数?

英文:

Q1. How do I create a golang time struct from a nanosecond timestamp?

Q2. How do I then compute the number of hours since this timestamp?

答案1

得分: 21

在Go语言中,"time"对象由time.Time结构类型的值表示。

你可以使用time.Unix(sec int64, nsec int64)函数从纳秒时间戳创建一个Time对象,其中可以传递超出范围[0, 999999999]nsec值。

你可以使用time.Since(t Time)函数,它返回自指定时间以来经过的时间,以time.Duration的形式表示(基本上是以纳秒为单位的时间差)。

t := time.Unix(0, yourTimestamp)
elapsed := time.Since(t)

要获取经过的小时数,只需使用Duration.Hours()方法,它以浮点数形式返回持续时间的小时数:

fmt.Printf("经过的时间:%.2f 小时", elapsed.Hours())

Go Playground上试一试。

注意:

Duration可以智能地以类似"72h3m0.5s"的格式进行格式化,这是通过其String()方法实现的:

fmt.Printf("经过的时间:%s", elapsed)
英文:

In Go a "time" object is represented by a value of the struct type time.Time.

You can create a Time from a nanosecond timestamp using the time.Unix(sec int64, nsec int64) function where it is valid to pass nsec outside the range [0, 999999999].

And you can use the time.Since(t Time) function which returns the elapsed time since the specified time as a time.Duration (which is basically the time difference in nanoseconds).

t := time.Unix(0, yourTimestamp)
elapsed := time.Since(t)

To get the elapsed time in hours, simply use the Duration.Hours() method which returns the duration in hours as a floating point number:

fmt.Printf("Elapsed time: %.2f hours", elapsed.Hours())

Try it on the Go Playground.

Note:

Duration can format itself intelligently in a format like "72h3m0.5s", implemented in its String() method:

fmt.Printf("Elapsed time: %s", elapsed)

答案2

得分: 5

你将纳秒传递给time.Unix(0, ts),示例代码如下:

func main() {
    now := time.Now()
    ts := int64(1257856852039812612)
    timeFromTS := time.Unix(0, ts)
    diff := now.Sub(timeFromTS)
    fmt.Printf("now: %v\ntime from ts: %v\ndiff: %v\ndiff int:", now, timeFromTS, diff, int64(diff))
}

playground

英文:

You pass the nanoseconds to time.Unix(0, ts), example:

func main() {
	now := time.Now()
	ts := int64(1257856852039812612)
	timeFromTS := time.Unix(0, ts)
	diff := now.Sub(timeFromTS)
	fmt.Printf("now: %v\ntime from ts: %v\ndiff: %v\ndiff int:", now, timeFromTS, diff, int64(diff))
}

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年2月27日 08:59:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/28755757.html
匿名

发表评论

匿名网友

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

确定