如何在golang中将Unix时间转换为time.Time类型?

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

How to convert Unix time to time.Time in golang?

问题

我可以帮你将Unix时间(1494505756)转换为UTC格式。你可以使用以下代码来实现:

import "time"

unixTime := int64(1494505756)
utcTime := time.Unix(unixTime, 0).UTC()

这将把Unix时间戳转换为UTC时间格式。你可以使用utcTime变量来获取转换后的时间。希望对你有帮助!

英文:

I want to covert Unix time (1494505756) to UTC format
just

import "time"
timeNow := time.Now()

I want to restore timeNow to UTC format. How to do that?

答案1

得分: 106

你可以从time接口本身获取UTC和unix时间。

要将unix时间戳转换为时间对象,请使用以下代码:

t := time.Unix(1494505756, 0)
fmt.Println(t)

time.Unix(sec int64, nsec int64)函数返回与给定的Unix时间相对应的本地时间。其中,sec表示自1970年1月1日UTC以来的秒数,nsec表示纳秒数。nsec的取值范围为[0, 999999999]。并非所有的sec值都有对应的时间值。其中一个特殊的值是1<<63-1(int64的最大值)。

获取UTC时间的方法如下:

time.Now().UTC()

UTC()函数返回一个具有UTC时区设置的时间对象。详细信息请参考链接:https://golang.org/pkg/time/#UTC

获取Unix时间的方法如下:

time.Now().Unix()

Unix()函数返回一个Unix时间,即自1970年1月1日UTC以来经过的秒数。详细信息请参考链接:https://golang.org/pkg/time/#Unix

英文:

You can get UTC and unix from time interface itself.

To convert unix timestamp to time object.
Use this:

t := time.Unix(1494505756, 0)
fmt.Println(t)

>func Unix(sec int64, nsec int64) Time

>Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

For UTC:

time.Now().UTC()

> UTC returns t with the location set to UTC.
> Link: https://golang.org/pkg/time/#UTC

For Unix:

time.Now().Unix()

> Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC.
Link: https://golang.org/pkg/time/#Unix

huangapple
  • 本文由 发表于 2017年5月11日 20:48:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/43915900.html
匿名

发表评论

匿名网友

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

确定