Nick
Nick

Reputation: 859

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?

Upvotes: 39

Views: 33370

Answers (4)

zenbro
zenbro

Reputation: 561

Time.strptime(milliseconds.to_s, '%Q')
// %Q - Number of milliseconds since 1970-01-01 00:00:00 UTC.

Upvotes: 54

Damien
Damien

Reputation: 27493

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

Upvotes: 69

shem
shem

Reputation: 4712

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 

Upvotes: 29

vigneshre
vigneshre

Reputation: 124

Time.parse("1379844601000") will give you the date and time

Upvotes: -1

Related Questions