In Rails, display time between two dates in English

前端 未结 6 551
南方客
南方客 2020-12-07 19:15

In a Rails project I want to find the difference between two dates and then display it in natural language. Something like

>> (date1 - date2).to_natur         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 20:00

    I tried Daniel's solution and found some incorrect results for a few test cases, due to the fact that it doesn't correctly handle the variable number of days found in months:

    > 30.days < 1.month
       => false
    

    So, for example:

    > d1 = DateTime.civil(2011,4,4)
    > d2 = d1 + 1.year + 5.months
    > time_diff_in_natural_language(d1,d2)
    => "1 year, 5 months, 3 days" 

    The following will give you the correct number of {years,months,days,hours,minutes,seconds}:

    def time_diff(from_time, to_time)
      %w(year month day hour minute second).map do |interval|
        distance_in_seconds = (to_time.to_i - from_time.to_i).round(1)
        delta = (distance_in_seconds / 1.send(interval)).floor
        delta -= 1 if from_time + delta.send(interval) > to_time
        from_time += delta.send(interval)
        delta
      end
    end
    > time_diff(d1,d2)
     => [1, 5, 0, 0, 0, 0] 

提交回复
热议问题