在 Ruby on Rails 中,如何使用“th”后缀格式化日期,例如“Sun Oct 5th”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/165170/
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
In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"?
提问by Jonathan Tran
I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix.
我想以以下格式显示日期:短星期几、短月份、不带前导零但包括“th”、“st”、“nd”或“rd”后缀的月份日期。
For example, the day this question was asked would display "Thu Oct 2nd".
例如,提出此问题的那天将显示“Thu Oct 2nd”。
I'm using Ruby 1.8.7, and Time.strftimejust doesn't seem to do this. I'd prefer a standard library if one exists.
我使用的是 Ruby 1.8.7,而Time.strftime似乎没有这样做。如果存在标准库,我更喜欢标准库。
回答by Bartosz Blimke
Use the ordinalize method from 'active_support'.
使用 'active_support' 中的 ordinalize 方法。
>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"
Note, if you are using IRB with Ruby 2.0, you must first run:
注意,如果你在 Ruby 2.0 中使用 IRB,你必须首先运行:
require 'active_support/core_ext/integer/inflections'
回答by mwilliams
You can use active_support's ordinalize helper method on numbers.
您可以对数字使用 active_support 的 ordinalize 辅助方法。
>> 3.ordinalize
=> "3rd"
>> 2.ordinalize
=> "2nd"
>> 1.ordinalize
=> "1st"
回答by Richard Hurt
Taking Patrick McKenzie's answer just a bit further, you could create a new file in your config/initializersdirectory called date_format.rb(or whatever you want) and put this in it:
进一步考虑 Patrick McKenzie 的回答,您可以在config/initializers名为date_format.rb(或任何您想要的)的目录中创建一个新文件并将其放入其中:
Time::DATE_FORMATS.merge!(
my_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") }
)
Then in your view code you can format any date simply by assigning it your new date format:
然后在您的视图代码中,您可以简单地通过为它分配新的日期格式来格式化任何日期:
My Date: <%= h some_date.to_s(:my_date) %>
It's simple, it works, and is easy to build on. Just add more format lines in the date_format.rb file for each of your different date formats. Here is a more fleshed out example.
它很简单,很有效,而且很容易构建。只需在 date_format.rb 文件中为每个不同的日期格式添加更多格式行。这是一个更充实的例子。
Time::DATE_FORMATS.merge!(
datetime_military: '%Y-%m-%d %H:%M',
datetime: '%Y-%m-%d %I:%M%P',
time: '%I:%M%P',
time_military: '%H:%M%P',
datetime_short: '%m/%d %I:%M',
due_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") }
)
回答by Jimmy Schementi
>> require 'activesupport'
=> []
>> t = Time.now
=> Thu Oct 02 17:28:37 -0700 2008
>> formatted = "#{t.strftime("%a %b")} #{t.day.ordinalize}"
=> "Thu Oct 2nd"
回答by Patrick McKenzie
I like Bartosz's answer, but hey, since this is Rails we're talking about, let's take it one step up in devious. (Edit: Although I was going to just monkeypatch the following method, turns out there is a cleaner way.)
我喜欢 Bartosz 的回答,但是嘿,既然我们正在谈论的是 Rails,让我们更狡猾地向前迈进一步。(编辑:虽然我打算只对以下方法进行猴子补丁,但事实证明有一种更清洁的方法。)
DateTimeinstances have a to_formatted_smethod supplied by ActiveSupport, which takes a single symbol as a parameter and, if that symbol is recognized as a valid predefined format, returns a String with the appropriate formatting.
DateTime实例具有to_formatted_sActiveSupport 提供的方法,该方法将单个符号作为参数,如果该符号被识别为有效的预定义格式,则返回具有适当格式的字符串。
Those symbols are defined by Time::DATE_FORMATS, which is a hash of symbols to either strings for the standard formatting function... or procs. Bwahaha.
这些符号由 定义Time::DATE_FORMATS,它是标准格式化函数的字符串或 procs 的符号散列。哇哈哈。
d = DateTime.now #Examples were executed on October 3rd 2008
Time::DATE_FORMATS[:weekday_month_ordinal] =
lambda { |time| time.strftime("%a %b #{time.day.ordinalize}") }
d.to_formatted_s :weekday_month_ordinal #Fri Oct 3rd
But hey, if you can't resist the opportunity to monkeypatch, you could always give that a cleaner interface:
但是,嘿,如果你无法抗拒猴子补丁的机会,你总是可以给它一个更干净的界面:
class DateTime
Time::DATE_FORMATS[:weekday_month_ordinal] =
lambda { |time| time.strftime("%a %b #{time.day.ordinalize}") }
def to_my_special_s
to_formatted_s :weekday_month_ordinal
end
end
DateTime.now.to_my_special_s #Fri Oct 3rd
回答by Joshua Pinter
Create your own %oformat.
创建您自己的%o格式。
Initializer
初始化程序
config/initializers/srtftime.rb
config/initializers/srtftime.rb
module StrftimeOrdinal
def self.included( base )
base.class_eval do
alias_method :old_strftime, :strftime
def strftime( format )
old_strftime format.gsub( "%o", day.ordinalize )
end
end
end
end
[ Time, Date, DateTime ].each{ |c| c.send :include, StrftimeOrdinal }
Usage
用法
Time.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"
You can use this with Dateand DateTimeas well:
您也可以将其与Date和一起使用DateTime:
DateTime.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"
Date.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"
回答by Olivier Lacan
Although Jonathan Tran did say he was looking for the abbreviated day of the week first followed by the abbreviated month, I think it might be useful for people who end up here to know that Rails has out-of-the-box support for the more commonly usable long month, ordinalized day integer, followed by the year, as in June 1st, 2018.
尽管 Jonathan Tran 确实说他首先寻找缩写的星期几,然后寻找缩写的月份,但我认为对于最终到达这里的人来说,知道 Rails 具有开箱即用的支持更多通常可用的长月份,有序日整数,后跟年份,如June 1st, 2018.
It can be easily achieved with:
它可以通过以下方式轻松实现:
Time.current.to_date.to_s(:long_ordinal)
=> "January 26th, 2019"
Or:
或者:
Date.current.to_s(:long_ordinal)
=> "January 26th, 2019"
You can stick to a time instance if you wish as well:
如果你愿意,你也可以坚持一个时间实例:
Time.current.to_s(:long_ordinal)
=> "January 26th, 2019 04:21"
You can find more formats and context on how to create a custom one in the Rails API docs.
您可以在Rails API 文档 中找到有关如何创建自定义格式的更多格式和上下文。

