Ruby-on-rails 格式化日期对象以显示人类可读的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11837171/
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
Formatting a date object to display a human readable date
提问by sergserg
Here's what I'd like to display:
这是我想显示的内容:
May 13, 2012
Here's what is being displayed:
这是显示的内容:
2012-05-13
I searched for some answers and it led me to "Formatting Dates and Floats in Ruby", where it mentions a possible solution:
我搜索了一些答案,它让我找到了“在 Ruby 中格式化日期和浮点数”,其中提到了一个可能的解决方案:
<p class="date"><%= @news_item.postdate.to_s("%B %d, %Y") %></p>
However this doesn't change the output at all. No debugging errors, or exceptions are fired.
然而,这根本不会改变输出。没有调试错误或异常被触发。
I can do this and it works perfectly fine:
我可以做到这一点,它工作得很好:
<p class="date"><%= Time.now.to_s("%B %d, %Y") %></p>
Here is my migration file (to see what data type I used):
这是我的迁移文件(查看我使用的数据类型):
class CreateNewsItems < ActiveRecord::Migration
def change
create_table :news_items do |t|
t.date :postdate
t.timestamps
end
end
end
回答by Casper
Date.to_sis not the same as Time.to_s. Your postdateis a Date, so therefore you might want to look at strftimeinstead:
Date.to_s不一样Time.to_s。您postdate是 a Date,因此您可能需要查看strftime:
postdate.strftime("%B %d, %Y")
Or even look to add your own custom date format to your Rails app:
Need small help in converting date format in ruby
或者甚至希望将您自己的自定义日期格式添加到您的 Rails 应用程序:
在 ruby 中转换日期格式需要一些帮助
回答by FernandoEscher
The to_formatted_sfunction already has some common human readable formats for DateTimeobjects in Rails.
该to_formatted_s功能已经有一些共同的人类可读的格式DateTime在Rails的对象。
datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
datetime.to_formatted_s(:short) # => "04 Dec 00:00"
datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
datetime.to_formatted_s(:iso8601) # => "2007-12-04T00:00:00+00:00"

