In Rails, display time between two dates in English

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

    def date_diff_in_natural_language(date_from, date_to)
      components = []
      %w(years months days).each do |interval_name|
        interval = 1.send(interval_name)
        count_intervals = 0
        while date_from + interval <= date_to
          date_from += interval
          count_intervals += 1
        end
        components << pluralize(count_intervals, interval_name) if count_intervals > 0
      end
      components.join(', ')
    end
    

提交回复
热议问题