json - 在 Go 中解析时间戳

标签 json parsing datetime go

我正在调用一个基于 JSON SIRI API 的服务,它以

的格式返回时间戳
"ResponseTimestamp": "/Date(1497923363000+0930)/"

这看起来像是自 Unix 纪元以来的毫秒数,加上本地时区偏移量。

标准的 Go 包是否包含解析这种格式的方法,如果有,它是什么?

我在这个网站和其他网站上搜索过解析、golang、时间戳、滴答声、纪元等术语。它在 JavaScript 的上下文中被提及,而不是 Go。我查看了这些包的 Go 源代码,但没有找到任何对此格式的引用。

我可以编写自己的函数来执行此操作,但我认为 Go 会包含该格式的解析器。

最佳答案

也许可以,但如果不是,您可以自己动手做:

pattern := regexp.MustCompile(`\A/Date\((\d+)([+-]\d+)\)/\z`)
m := pattern.FindStringSubmatch(res.ResponseTimestamp)
if len(m) == 0 {
    // Handle error: not a datetime in the expected format
}

// Get the milliseconds part
ms, err := strconv.Parseint(m[1], 10, 64)
// Handle err (in the rare case of, say, an out of range error)

// Use Go's time parser to parse the timezone part
tForLoc, err := time.Parse("-0700", m[2])
// Handle err (invalid timezone spec)

// Combine the milliseconds, the timezone, and the Unix epoch
t := time.Date(1970, 1, 1, 0, 0, 
    int(ms/1000), int((ms%1000)*1e6, tForLoc.Location())

return t

关于json - 在 Go 中解析时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44644412/

相关文章:

javascript - Ember - 如何清理 JSON 响应

parsing - SLR(1) 或 LR(1) 解析

linux - 在 Python3 中使用 HTMLParser 解析 HTML

javascript - 在 JavaScript 中在给定日期时间执行代码的最佳方式

java - 我如何解析 JSON 的这种语法?

android - 如何使 fragment 中的 RecyclerView 可点击?

java - 解析 JSON 并转换为对象列表

php - 如何避免DOM解析添加html doctype、<head>和<body>标签?

c++ - 使用 boost::date_time 库以毫秒为单位格式化时间

php - 格式化 DateTime Diff 以防止在 PHP 中显示 0 年 0 个月