How do you do relative time in Rails?

前端 未结 11 1614
借酒劲吻你
借酒劲吻你 2020-12-02 03:43

I\'m writing a Rails application, but can\'t seem to find how to do relative time, i.e. if given a certain Time class, it can calculate \"30 seconds ago\" or \"2 days ago\"

11条回答
  •  忘掉有多难
    2020-12-02 04:35

    Something like this would work.

    def relative_time(start_time)
      diff_seconds = Time.now - start_time
      case diff_seconds
        when 0 .. 59
          puts "#{diff_seconds} seconds ago"
        when 60 .. (3600-1)
          puts "#{diff_seconds/60} minutes ago"
        when 3600 .. (3600*24-1)
          puts "#{diff_seconds/3600} hours ago"
        when (3600*24) .. (3600*24*30) 
          puts "#{diff_seconds/(3600*24)} days ago"
        else
          puts start_time.strftime("%m/%d/%Y")
      end
    end
    

提交回复
热议问题