Parse ticks to datetime

2020-02-12 10:09发布

How can I convert a tick, such as 1298011537289 to a DateTime in Ruby?

The value I need to convert is coming from a JavaScript Date.now() call, so it's in milliseconds

标签: ruby
3条回答
女痞
2楼-- · 2020-02-12 10:48

Per the Ruby docs:

myTime = Time.at(1298011537289)

or since you're using milliseconds rather than seconds:

myTime = Time.at(1298011537289 / 1000)

But that will only remove sub-second precision, to retain it:

myTime = Time.at(Rational(1298011537289, 1000))
查看更多
Explosion°爆炸
3楼-- · 2020-02-12 10:48

Use strptime and parse it with the format %Q - Number of microseconds since 1970-01-01 00:00:00 UTC.

Example: DateTime.strptime "1352748750274", "%Q"

查看更多
Lonely孤独者°
4楼-- · 2020-02-12 11:14

Assuming the value is in milliseconds, this is how I'd do it:

require 'date'
DateTime.parse(Time.at(1298011537289 / 1000).to_s) # => #<DateTime: 2011-02-17T23:45:37-07:00 (212164771537/86400,-7/24,2299161)>
查看更多
登录 后发表回答