programing

레일즈에서 상대적인 시간은 어떻게 됩니까?

elecom 2023. 6. 12. 21:07
반응형

레일즈에서 상대적인 시간은 어떻게 됩니까?

Rails 애플리케이션을 작성하고 있지만 상대적인 시간을 수행하는 방법을 찾을 수 없습니다. 즉, 특정 Time 클래스가 주어지면 "30초 전" 또는 "2일 전"을 계산하거나 한 달 이상 "2008년 9월 1일"을 계산할 수 있습니다.

ActiveSupport에서 메서드(또는 )를 찾고 있는 것 같습니다.다음과 같이 부릅니다.

<%= 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

단지 시간_ago_in_words를 사용하는 Andrew Marshall의 솔루션을 명확히 하기 위해.
(레일 3.0 및 레일 4.0용)

보기에 있는 경우

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

컨트롤러에 있는 경우

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

컨트롤러에는 ActionView 모듈이 없습니다.: 도우미::DateHelper를 기본적으로 가져옵니다.

N.B. 도우미를 컨트롤러로 가져오는 것은 "철도"가 아닙니다.도우미는 보기를 돕기 위한 것입니다.time_ago_in_words 메서드는 MVC 트라이어에서 뷰 엔티티로 결정되었습니다.(동의하지 않지만 로마에 있을 때는...)

어때

30.seconds.ago
2.days.ago

아니면 당신이 촬영하고 있던 다른 것?

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

Time.now - 2.days 

이틀 전에 드리겠습니다.

이런 것도 가능할 겁니다.

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) %>

레일에서 다음을 선호합니다.

<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/

여기서 인스턴스 메소드를 살펴봅니다.

http://apidock.com/rails/Time

이것은 어제, 내일, begining_of_week, ago 등과 같은 유용한 방법을 가지고 있습니다.

예:

Time.now.yesterday
Time.now.ago(2.days).end_of_day
Time.now.next_month.beginning_of_month

Rails 응용프로그램을 작성하는 경우 다음을 사용해야 합니다.

Time.zone.now
Time.zone.today
Time.zone.yesterday

이렇게 하면 레일즈 응용프로그램을 구성한 시간대의 시간 또는 날짜가 표시됩니다.

예를 들어 UTC를 사용하도록 응용 프로그램을 구성하는 경우Time.zone.now항상 UTC 시간으로 표시됩니다(예를 들어 영국 서머타임 변경에 영향을 받지 않음).

상대 시간을 계산하는 것은 쉽습니다.

Time.zone.now - 10.minute
Time.zone.today.days_ago(5)

Rails ActiveRecord 개체에 대해 이 기능을 수행하는 보석을 작성했습니다.이 예제에서는 created_at을 사용하지만, ActiveSupport:: 클래스가 있는 updated_at 또는 기타 클래스에서도 작동합니다.TimeWithZone.

TimeWithZone 인스턴스에 gem을 설치하고 '예쁜' 메서드를 호출하기만 하면 됩니다.

https://github.com/brettshollenberger/hublot

또 다른 접근 방식은 백엔드에서 일부 논리를 언로드하고 다음과 같은 Javascript 플러그인을 사용하여 브라우저가 작업을 수행하도록 맥 처리하는 것입니다.

jQuery time ago 또는 해당 Rails Gem 적응

언급URL : https://stackoverflow.com/questions/195740/how-do-you-do-relative-time-in-rails

반응형