[ruby-on-rails] Rails에서 상대 시간은 어떻게합니까?

Rails 애플리케이션을 작성하고 있지만 상대 시간을 수행하는 방법을 찾지 못하는 것 같습니다. 예를 들어 특정 Time 클래스가 지정된 경우 “30 초 전”또는 “2 일 전”또는 1 개월 이상인 경우 계산할 수 있습니다 “2008 년 9 월 1 일”등



답변

ActiveSupport에서 time_ago_in_words메소드 (또는 distance_of_time_in_words)를 찾고있는 것처럼 들립니다. 다음과 같이 호출하십시오.

<%= time_ago_in_words(timestamp) %>


답변

나는 이것을 작성했지만 더 나은지 확인하기 위해 언급 된 기존 방법을 확인해야합니다.

module PrettyDate
  def to_pretty
    a = (Time.now-self).to_i

    case a
      when 0 then 'just now'
      when 1 then 'a second ago'
      when 2..59 then a.to_s+' seconds ago' 
      when 60..119 then 'a minute ago' #120 = 2 minutes
      when 120..3540 then (a/60).to_i.to_s+' minutes ago'
      when 3541..7100 then 'an hour ago' # 3600 = 1 hour
      when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' 
      when 82801..172000 then 'a day ago' # 86400 = 1 day
      when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'
      when 518400..1036800 then 'a week ago'
      else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
    end
  end
end

Time.send :include, PrettyDate


답변

time_ago_in_words

(Rails 3.0 및 Rails 4.0) 를 사용하기위한 Andrew Marshall의 솔루션을 명확히하기 위해

당신이 볼 수 있다면

<%= time_ago_in_words(Date.today - 1) %>

당신이 컨트롤러에있는 경우

include ActionView::Helpers::DateHelper
def index
  @sexy_date = time_ago_in_words(Date.today - 1)
end

컨트롤러에는 ActionView :: Helpers :: DateHelper 모듈 을 기본적으로 가져 오지 않습니다 .

NB 헬퍼를 컨트롤러로 가져 오는 것은 “레일 방식”이 아닙니다. 도우미는 뷰를 돕는 데 도움이됩니다. time_ago_in_words의 방법은 것으로 결정되었다 엔터티 MVC의 화음. (나는 동의하지 않지만 로마에있을 때 …)


답변

이건 어떤가요

30.seconds.ago
2.days.ago

아니면 당신이 촬영 한 다른 것이 있습니까?


답변

산술 연산자를 사용하여 상대 시간을 수행 할 수 있습니다.

Time.now - 2.days 

2 일 전에 드리겠습니다.


답변

이런 식으로 작동합니다.

def relative_time(start_time)
  diff_seconds = Time.now - start_time
  case diff_seconds
    when 0 .. 59
      puts "#{diff_seconds} seconds ago"
    when 60 .. (3600-1)
      puts "#{diff_seconds/60} minutes ago"
    when 3600 .. (3600*24-1)
      puts "#{diff_seconds/3600} hours ago"
    when (3600*24) .. (3600*24*30) 
      puts "#{diff_seconds/(3600*24)} days ago"
    else
      puts start_time.strftime("%m/%d/%Y")
  end
end


답변

여기에 가장 답변이 많으므로 time_ago_in_words가 제안 됩니다 .

사용하는 대신 :

<%= time_ago_in_words(comment.created_at) %>

Rails에서 선호하는 사항 :

<abbr class="timeago" title="<%= comment.created_at.getutc.iso8601 %>">
  <%= comment.created_at.to_s %>
</abbr>

코드와 함께 jQuery 라이브러리 http://timeago.yarp.com/ 과 함께 :

$("abbr.timeago").timeago();

주요 장점 : 캐싱

http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/