解析 JSON 日期时间? [英] Parsing JSON datetime?

查看:61
本文介绍了解析 JSON 日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个 JSON API,它将日期时间值作为以下格式的字符串返回:

I am consuming a JSON API that returns datetime values as a string in the following format:

/日期(1370651105153)/

/Date(1370651105153)/

如何将这样的值解析为 rails 中的日期时间变量?

How can I parse a value like this into a datetime variable in rails?

推荐答案

这似乎是一个 UNIX 时间戳(自纪元以来的秒数).此外,它似乎是自纪元以来的毫秒数.

That appears to be a UNIX timestamp (seconds since epoch). Additionally it appears to be milliseconds since epoch.

所以你可以像这样转换它 - 鉴于 value 是一个看起来像的字符串:

So you can convert it like so - given that value is a String that looks like:

value = "/Date(1370651105153)/"

if value =~ /\/Date\((\d+)\)\//
  timestamp = $1.to_i
  time = Time.at(timestamp / 1000)
  # time is now a Time object
end

您需要除以 1000,因为 Time#at 期望它的参数是自纪元以来的秒数而不是毫秒数.

You need to divide by 1000 since Time#at expects its argument to be seconds and not milliseconds since the epoch.

这篇关于解析 JSON 日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆