Srikanth Bhandary
Srikanth Bhandary

Reputation: 1747

Convert epoch time in Ruby (Long string)

Epoch time with leading 3 zeros is returning an invalid year.

Time.at(1520486517000).to_datetime
 => Wed, 19 Apr 50152 19:20:00 +0530 

After removing ending 3 zeros, it's returning and valid time stamp.

Time.at(1520486517).utc.to_datetime
=> Thu, 08 Mar 2018 05:21:57 +0000 

Is there any way in ruby to churn the epoch time to valid timestamp, when the input has lengthy epoch numbers?

Upvotes: 0

Views: 248

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Use DateTime#strptime with "%Q" formatter for parsing milliseconds.

require 'date'
DateTime.strptime 1520486517000.to_s, '%Q'
#⇒ #<DateTime: 2018-03-08T05:21:57+00:00 ((2458186j,19317s,0n),+0s,2299161j)>

Upvotes: 3

Srikanth Bhandary
Srikanth Bhandary

Reputation: 1747

I have found the following way to handle the long timestamp.

https://www.ruby-forum.com/topic/85822

Time.at(1520486517000/1000).utc.to_datetime
 => Thu, 08 Mar 2018 05:21:57 +0000 

Upvotes: -1

Related Questions