Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert milliseconds to formatted date in Rails

I'm sure this should be simple (probably missing something obvious), but... I have a database string of milliseconds I want to convert into a US-formatted date in Rails. Figured calling .to_date would be my friend, but it's throwing a strange error.

article.date => "1379844601000"

article.date.to_date
NoMethodError: undefined method `div' for nil:NilClass

Can anyone advise the correct way to do this?

like image 996
Nick Avatar asked Sep 22 '13 10:09

Nick


3 Answers

Convert it to seconds (milliseconds/1000) and call Time::at on the result:

Time.at(1379844601000/1000) # => 2013-09-22 12:10:01 +0200 

Time::at on ruby-doc.org

like image 129
Damien Avatar answered Oct 07 '22 02:10

Damien


Time.strptime(milliseconds.to_s, '%Q')
// %Q - Number of milliseconds since 1970-01-01 00:00:00 UTC.
like image 20
zenbro Avatar answered Oct 07 '22 00:10

zenbro


Use Date.strptime- but before this, convert it to seconds first:

sec = ('1379844601000'.to_f / 1000).to_s
Date.strptime(sec, '%s')
//Sun, 22 Sep 2013 
like image 34
shem Avatar answered Oct 07 '22 01:10

shem