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/
여기에서 인스턴스 메소드를 살펴보십시오.
여기에는 어제, 내일, 시작 _ 주, 전 등과 같은 유용한 방법이 있습니다.
예 :
Time.now.yesterday
Time.now.ago(2.days).end_of_day
Time.now.next_month.beginning_of_month
Rails ActiveRecord 객체를 위해 보석을 작성했습니다. 이 예제에서는 created_at을 사용하지만 updated_at 또는 ActiveSupport :: TimeWithZone 클래스의 모든 항목에서도 작동합니다.
보석을 설치하고 TimeWithZone 인스턴스에서 'pretty'메소드를 호출하십시오.
https://github.com/brettshollenberger/hublot
Rails 애플리케이션을 구축하는 경우
Time.zone.now
Time.zone.today
Time.zone.yesterday
이를 통해 Rails 애플리케이션을 구성한 시간대의 시간 또는 날짜가 제공됩니다.
예를 들어, UTC를 사용하도록 응용 프로그램을 구성 Time.zone.now
하면 항상 UTC 시간이됩니다 (예를 들어 영국 서머 타임 변경에 영향을받지 않음).
상대 시간 계산이 쉽습니다. 예 :
Time.zone.now - 10.minute
Time.zone.today.days_ago(5)
또 다른 방법은 백엔드에서 일부 로직을 언로드하고 브라우저가 다음과 같은 Javascript 플러그인을 사용하여 작업을 수행하는 것입니다.
참고 URL : https://stackoverflow.com/questions/195740/how-do-you-do-relative-time-in-rails
'Programing' 카테고리의 다른 글
생성자가 Java에서 예외를 발생시킬 수 있습니까? (0) | 2020.04.21 |
---|---|
데몬 스레드 설명 (0) | 2020.04.21 |
SSL 핸드 셰이크 경고 : Java 1.7.0으로 업그레이드 한 후 unrecognized_name 오류 (0) | 2020.04.21 |
트위터 부트 스트랩 2에 버튼을 제출하기 위해 아이콘 추가 (0) | 2020.04.21 |
사용자가 로그인했는지 확인하는 방법 (user.is_authenticated를 올바르게 사용하는 방법)? (0) | 2020.04.21 |