이 두 날짜 사이의 일수를 어떻게 계산합니까?
start_date = Date.parse "2012-03-02 14:46:21 +0100"
end_date = Date.parse "2012-04-02 14:46:21 +0200"
답변
Date (및 DateTime) 클래스를 사용하면 (end_date - start_date).to_i
일 수 차이를 얻을 수 있습니다 .
답변
그 가정 end_date
및 start_date
클래스의 모두 ActiveSupport::TimeWithZone
레일에, 당신은 사용할 수 있습니다 :
(end_date.to_date - start_date.to_date).to_i
답변
Rails에는 이를 해결할 수 있는 내장 된 도우미 가 있습니다. 명심해야 할 것은 이것이 Actionview 헬퍼의 일부이므로 콘솔에서 직접 사용할 수 없다는 것입니다.
이 시도
<% start_time = "2012-03-02 14:46:21 +0100" %>
<% end_time = "2012-04-02 14:46:21 +0200" %>
<%= distance_of_time_in_words(start_time, end_time) %>
"about 1 month"
답변
몇 초 만에 결과를 얻었으므로 이것이 효과가있었습니다.
(Time.now - self.created_at) / 86400
답변
시간 범위에서 일 수를 얻으려면 (모든 일 수)
(start_date..end_date).count
(start_date..end_date).to_a.size
#=> 32
두 날짜 사이의 일 수를 얻으려면
(start_date...end_date).count
(start_date...end_date).to_a.size
#=> 31
답변
이 날짜까지의 이전 답변 중 어느 것도 두 날짜 사이의 정확한 차이를 제공하지 않습니다.
가장 가까운 것은 thatdankent 입니다. 완전한 대답은 to_i
다음과 같이 변환 하고 나눕니다.
(Time.now.to_i - 23.hours.ago.to_i) / 86400
>> 0
(Time.now.to_i - 25.hours.ago.to_i) / 86400
>> 1
(Time.now.to_i - 1.day.ago.to_i) / 86400
>> 1
질문의 특정 예에서, Date
통과 된 시간이 관련이 있는지 구문 분석해서는 안됩니다 . Time.parse
대신 사용하십시오 .
답변
두 날짜 ( DateTime
오브젝트) 사이의 하루 수를 유지하려면 다음을 수행하십시오 .
((end_at - start_at).to_f / 1.day).floor
