string - 将 int64(来自 UnixNano)转换为位置时间字符串

标签 string go time

我有一个 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 与您提供的字符串不对应。

相关文档:

https://golang.org/pkg/time/#Unix

https://golang.org/pkg/fmt/

关于string - 将 int64(来自 UnixNano)转换为位置时间字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45679529/

相关文章:

bash - 从 golang 代码重新加载或获取/etc/enviornment 文件

java - 每次循环迭代时,我可以将不同的信息从 for 循环返回到新变量吗?

string - Julia:字符串的空向量

python - 在字符串格式中调用类方法

go - 你如何在 GoLang 的模拟中模拟错误返回值?

inheritance - 从基类分配到 Go 中的继承类

linux - Bash 时差计算

具有 "+00"时区偏移格式的 Python strptime?

C++ 获取毫秒时间

string - 将 String.Index 转换为 Int 或将 Range<String.Index> 转换为 NSRange