In Rails, display time between two dates in English

前端 未结 6 541
南方客
南方客 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:05

    The other answers may not give the type of output that you're looking for, because instead of giving a string of years, months, etc., the Rails helpers just show the largest unit. If you're looking for something more broken down, here's another option. Stick this method into a helper:

    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)
          # if above line give pain. try below one  
          # components <<  interval.pluralize(delta)  
        end
      end
    
      components.join(", ")
    end
    

    And then in a view you can say something like:

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

    The given method only goes down to days, but can be easily extended to add in smaller units if desired.

提交回复
热议问题