Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse ticks to datetime

Tags:

ruby

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

like image 799
Aaron Powell Avatar asked Dec 03 '22 03:12

Aaron Powell


2 Answers

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))
like image 69
Andrew Marshall Avatar answered Jan 20 '23 11:01

Andrew Marshall


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"

like image 35
brutuscat Avatar answered Jan 20 '23 11:01

brutuscat