2011-03-29 5 views
2

가 나는 일수의 날짜의 차이를 반환 것 같다 루비 날짜 빼기

"2011-03-29".to_date - "2011-03-20".to_date #=> (9/1) 
("2011-03-29".to_date - "2011-03-20".to_date).to_i #=> 9 

루비

날짜 빼기에 문제가 있습니다.

지금 내 문제는 년의 수를 반환하는 것입니다, 달, 날짜 차이

ie ("2011-03-29".to_date - "2011-03-20".to_date) 

의 일

0 years, 0 month and 9 days 

감사를 반환해야합니다.

당신은이 링크를 시도 할 수 있습니다
+0

문자열에'to_date' 메소드를 제공하는 라이브러리 나 프레임 워크는 무엇입니까? 울타리? 다른 것? – maerics

답변

1

:

http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words

또는

def time_diff_in_natural_language(from_time, to_time) 
    from_time = from_time.to_time if from_time.respond_to?(:to_time) 
    to_time = to_time.to_time if to_time.respond_to?(:to_time) 
    distance_in_seconds = ((to_time - from_time).abs).round 
    components = [] 

    %w(year month week day).each do |interval| 
     # For each interval type, if the amount of time remaining is greater than 
     # one unit, calculate how many units fit into the remaining time. 
     if distance_in_seconds >= 1.send(interval) 
     delta = (distance_in_seconds/1.send(interval)).floor 
     distance_in_seconds -= delta.send(interval) 
     components << pluralize(delta, interval) 
     end 
    end 

    components.join(", ") 
    end 

    time_diff_in_natural_language(Time.now, 2.5.years.ago) 
    >> 2 years, 6 months, 2 days 

참조 : In Rails, display time between two dates in English

+0

방위를 프로그램하지 마십시오. – Reactormonk

+1

방위는? 제발 좀 더 자세히 설명해주세요. –

+0

나는 그것이 무엇을 의미하는지 안다 ... 나는 to_time 방법을 시간에서 확인했다. 바로 Tass ??? – Ashish

1

내가 좀 지저분 알고 있지만 당신이 시도가 :

result = Date.new(0) + ("2011-03-29".to_date - "2011-03-20".to_date) 
puts "#{result.year} years, #{result.month - 1} months and #{result.day} days" 
+0

# u가 # {result.month-1}을 (를) 놓친 것 같습니다. Date.new (0)은 1 월을 1 달로 취하기 때문입니다. – a5his

+0

당신이 옳습니다. 몇 달이 시작됩니다. 방금 답변을 업데이트했습니다. Tks. – Edu