Programing

Ruby on Rails에서 "Sun Oct 5th"와 같이 "th"접미사로 날짜를 어떻게 형식화합니까?

lottogame 2020. 5. 24. 10:44
반응형

Ruby on Rails에서 "Sun Oct 5th"와 같이 "th"접미사로 날짜를 어떻게 형식화합니까?


짧은 주중, 짧은 달, 앞에 0이없는 "th", "st", "nd"또는 "rd"접미사를 포함한 형식으로 날짜를 표시하고 싶습니다.

예를 들어,이 질문을받은 날에는 "Thu Oct 2nd"가 표시됩니다.

Ruby 1.8.7을 사용하고 있으며 Time.strftime 은이 작업을 수행하지 않는 것 같습니다. 표준 라이브러리가 있으면 선호합니다.


'active_support'의 서 수화 방법을 사용하십시오.

>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"

Ruby 2.0에서 IRB를 사용하는 경우 먼저 다음을 실행해야합니다.

require 'active_support/core_ext/integer/inflections'

숫자에 active_support의 서수 도우미 메소드를 사용할 수 있습니다.

>> 3.ordinalize
=> "3rd"
>> 2.ordinalize
=> "2nd"
>> 1.ordinalize
=> "1st"

Patrick McKenzie의 답변을 조금 더 가져 가면 config/initializers디렉토리에 date_format.rb(또는 원하는대로) 새 파일을 만들고 이것을 넣을 수 있습니다.

Time::DATE_FORMATS.merge!(
  my_date: lambda { |time| time.strftime("%a, %b #{time.day.ordinalize}") }
)

그런 다음 뷰 코드에서 새 날짜 형식을 지정하여 날짜를 간단히 형식 지정할 수 있습니다.

My Date: <%= h some_date.to_s(:my_date) %>

간단하고 작동하며 쉽게 구축 할 수 있습니다. 다른 날짜 형식 각각에 대해 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}") }
)

>> require 'activesupport'
=> []
>> t = Time.now
=> Thu Oct 02 17:28:37 -0700 2008
>> formatted = "#{t.strftime("%a %b")} #{t.day.ordinalize}"
=> "Thu Oct 2nd"

나는 Bartosz의 대답이 마음에 들지만, 우리가 말하는 Rails이기 때문에 한 단계 씩 악의적으로 다루어 봅시다. (편집 : 다음과 같은 방법으로 원숭이 패치를하려고했지만 더 깨끗한 방법이 있습니다.)

DateTime인스턴스에는 to_formatted_s단일 기호를 매개 변수로 사용하는 ActiveSupport에서 제공 하는 메소드 가 있으며 해당 기호가 유효한 사전 정의 된 형식으로 인식되면 적절한 형식의 문자열을 리턴합니다.

이러한 기호는 Time::DATE_FORMATS표준 형식화 함수 또는 procs의 문자열에 대한 기호의 해시 인에 의해 정의됩니다 . Bwahaha.

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

그러나 원숭이 패치의 기회를 막을 수 없다면 항상 깨끗한 인터페이스를 제공 할 수 있습니다.

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

나만의 %o형식을 만드십시오 .

이니셜 라이저

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 }

용법

Time.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"

당신은 이것을 사용할 수 있습니다 DateDateTime뿐만 아니라 :

DateTime.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"

Date.new( 2018, 10, 2 ).strftime( "%a %b %o" )
=> "Tue Oct 2nd"

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.

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.

참고URL : https://stackoverflow.com/questions/165170/in-ruby-on-rails-how-do-i-format-a-date-with-the-th-suffix-as-in-sun-oct-5

반응형