Ruby-on-rails 将毫秒转换为 Rails 中的格式化日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18942816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert milliseconds to formatted date in Rails
提问by Nick
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_datewould be my friend, but it's throwing a strange error.
我确定这应该很简单(可能缺少一些明显的东西),但是...我有一个毫秒的数据库字符串,我想在 Rails 中将其转换为美国格式的日期。.to_date想打电话是我的朋友,但它抛出了一个奇怪的错误。
article.date => "1379844601000"
article.date.to_date
NoMethodError: undefined method `div' for nil:NilClass
Can anyone advise the correct way to do this?
谁能建议正确的方法来做到这一点?
采纳答案by shem
Use Date.strptime- but before this, convert it to seconds first:
使用Date.strptime- 但在此之前,先将其转换为秒:
sec = ('1379844601000'.to_f / 1000).to_s
Date.strptime(sec, '%s')
//Sun, 22 Sep 2013
回答by Damien
Convert it to seconds (milliseconds/1000)and call Time::aton the result:
将其转换为秒(milliseconds/1000)并调用Time::at结果:
Time.at(1379844601000/1000)
# => 2013-09-22 12:10:01 +0200
回答by zenbro
Time.strptime(milliseconds.to_s, '%Q')
// %Q - Number of milliseconds since 1970-01-01 00:00:00 UTC.
回答by vigneshre
Time.parse("1379844601000") will give you the date and time
Time.parse("1379844601000") 会给你日期和时间

