2012-08-06 2 views
24

를 표시하는 내가 표시 할 내용은 다음과 같습니다날짜 객체를 포맷하면 인간이 읽을 수있는 날짜 여기

May 13, 2012 

여기에 표시되는 내용은 다음과 같습니다

2012-05-13 

내가 어떤 답을 검색하고 주도 나 "Formatting Dates and Floats in Ruby", 그것은 가능한 해결책 언급 어디에합니다 :

<p class="date"><%= @news_item.postdate.to_s("%B %d, %Y") %></p> 

을하지만이 일 변경되지 않습니다 전자 출력. 디버깅 오류 또는 예외가 발생하지 않습니다.

나는이 작업을 수행 할 수 있으며 완벽하게 잘 작동 : 여기

<p class="date"><%= Time.now.to_s("%B %d, %Y") %></p> 

내 마이그레이션 파일입니다 (내가 사용하는 어떤 데이터 유형 볼 수) :

class CreateNewsItems < ActiveRecord::Migration 
    def change 
    create_table :news_items do |t| 

     t.date :postdate 

     t.timestamps 
    end 
    end 
end 

답변

44

Date.to_sTime.to_s과 동일하지 않습니다 . 이미
Need small help in converting date format in ruby

+0

도 참조 - http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime – JGrubb

+8

하나의 작은 노트'의 strftime ("% B 형 %의 -d , % Y ")'는 인간의 가독성을 위해 약간 더 좋다. '% -d'는 선행 0 즉, 2013 년 5 월 6 일 => 2013 년 5 월 6 일을 제거합니다. –

29

to_formatted_s 기능 : 당신의 레일 응용 프로그램에 사용자 정의 날짜 형식을 추가 할

postdate.strftime("%B %d, %Y") 

을 심지어 모양 : 당신의 postdate 그렇게 때문에 대신 strftime보고 할 수 있습니다하는 Date입니다 Rails에는 DateTime 오브젝트에 대해 사람이 읽을 수있는 형식이 있습니다.

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" 
+5

은 _to_s_와 별칭을가집니다. –

관련 문제