将日期时间转换为月,日和年?
我似乎无法找到这个,我觉得它应该很容易。 在Ruby on Rails中,我该如何处理:
2010-06-14 19:01:00 UTC
把它变成
June 14th, 2010
我不能只在视图中使用帮助器吗?
我不知道
June 14th, 2010
但如果你想要
June 14, 2010
参考如何在Rails上获取ruby中的月份名称? 或者这个
做就是了
@date = Time.now @date.strftime("%B %d, %Y")
并为后缀使用以下
@date.strftime("%B #{@date.day.ordinalize}, %Y") # >>> Gives `June 18th, 2010`
供将来参考: Rails日期时间格式
rails中的时间和日期格式:
日期
====
db:'%Y-%m-%d' 2008-08-20 long_ordinal:'&proc' August 20th, 2008 long:'%B %e, %Y' August 20, 2008 rfc822:'%e %b %Y' 20 Aug 2008 number:'%Y%m%d' 20080820 short:'%e %b' 20 Aug
约会时间
====
db:'%Y-%m-%d' 2008-08-20 16:56:21 long_ordinal:'&proc' August 20th, 2008 16:56 long:'%B %e, %Y' August 20, 2008 16:56 rfc822:'%e %b %Y' Wed, 20 Aug 2008 16:56:21 -0600 number:'%Y%m%d' 20080820165621 short:'%e %b' 20 Aug 16:56
时间
====
db:'%Y-%m-%d %H:%M:%S' 2008-08-20 16:56:21 long_ordinal:'&proc' August 20th, 2008 16:56 long:'%B %d, %Y %H:%M' August 20, 2008 16:56 rfc822:'%a, %d %b %Y %H:%M:%S %z' Wed, 20 Aug 2008 16:56:21 -0600 short:'%d %b %H:%M' 20 Aug 16:56 number:'%Y%m%d%H%M%S' 20080820165621 time:'%H:%M' 16:56
例如:
<%= news.created_at.strftime("%B %d, %Y %H:%M") %>
谢谢http://onrails.org/2008/08/20/what-are-all-the-rails-date-formats.html
您不需要将其保存在变量中。
Time.now.strftime("%Y-%m-%d") # 2013-01-08
需要Time.parse
的Time模块和Integer#ordinalize
ActiveSupport:
require 'time' require 'active_support' input = '2010-06-14 19:01:00 UTC' t = Time.parse(input) date = "%s %s, %d" % [t.strftime("%B"), t.day.ordinalize, t.year] # => "June 14th, 2010"
别忘了,ruby在轨道上:D
就在前几天有一个类似的问题。 在我的回答中如何在Rails上获取ruby中月份的名称? 我展示了如何在config/environment.rb
文件中添加自定义to_s
定义。
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!( :my_own_long_date_format => "%B %d, %Y")
现在,您可以从任何视图调用Time.now.to_s(:my_own_long_date_format)
来获取:
June 15, 2010