我有一个 int64 像:
1502712864232
这是对服务的 REST GET 的结果。我可以很容易地将它转换为字符串。它是一个 Unixnano 时间戳。
我真正需要的是将其转换为与时区(如“欧洲/伦敦”)相关的字符串。如:-
"14/08/2017, 13:14:24"
例如由这个方便的实用程序生成的: http://www.freeformatter.com/epoch-timestamp-to-date-converter.html
非常感谢任何帮助。
==> 更新。
感谢@evanmcdonnal 提供了如此有用的答案。非常感激。 事实证明,我拥有的数据根本不是 UnixNano(抱歉),它距离 Epoch 仅几毫秒。来源是 Jenkins 时间戳....
所以...我编写了以下辅助函数来获得我需要的东西:
// Arg 1 is an int64 representing the millis since Epoch
// Arg 2 is a timezome. Eg: "Europe/London"
// Arg 3 is an int relating to the formatting of the returned string
// Needs the time package. Obviously.
func getFormattedTimeFromEpochMillis(z int64, zone string, style int) string {
var x string
secondsSinceEpoch := z / 1000
unixTime := time.Unix(secondsSinceEpoch, 0)
timeZoneLocation, err := time.LoadLocation(zone)
if err != nil {
fmt.Println("Error loading timezone:", err)
}
timeInZone := unixTime.In(timeZoneLocation)
switch style {
case 1:
timeInZoneStyleOne := timeInZone.Format("Mon Jan 2 15:04:05")
//Mon Aug 14 13:36:02
return timeInZoneStyleOne
case 2:
timeInZoneStyleTwo := timeInZone.Format("02-01-2006 15:04:05")
//14-08-2017 13:36:02
return timeInZoneStyleTwo
case 3:
timeInZoneStyleThree := timeInZone.Format("2006-02-01 15:04:05")
//2017-14-08 13:36:02
return timeInZoneStyleThree
}
return x
}
最佳答案
与其将其转换为字符串,不如将其转换为 time.Time
,然后从那里转换为字符串。您可以使用方便的 Unix
方法为该时间戳返回一个 Time
对象。
import "time"
import "fmt"
t := time.Unix(0, 1502712864232)
fmt.Println(t.Format("02/01/2006, 15:04:05"))
编辑:为 println 添加了格式 - 注意,在 go playground 中测试你的 unix 戳记,该值既不是纳秒也不是秒,在这两种情况下,产生的时间值都与它应该的值相去甚远。上面的代码仍然演示了您想要做什么的基本思想,但似乎还需要一个额外的步骤,或者您提供的示例 int64
与您提供的字符串不对应。
相关文档:
关于string - 将 int64(来自 UnixNano)转换为位置时间字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45679529/