Ruby/Rails - How to convert seconds to time?

后端 未结 4 1746
既然无缘
既然无缘 2021-02-19 16:52

I need to perform the following conversion:

0     -> 12.00AM
1800  -> 12.30AM
3600  -> 01.00AM
...
82800 -> 11.00PM
84600 -> 11.30PM
4条回答
  •  清酒与你
    2021-02-19 17:30

    Two offers:

    The elaborate DIY solution:

    def toClock(secs)
      h = secs / 3600;  # hours
      m = secs % 3600 / 60; # minutes
      if h < 12 # before noon
        ampm = "AM"
        if h = 0
          h = 12
        end
      else     # (after) noon
        ampm =  "PM"
        if h > 12
          h -= 12
        end
      end
      ampm = h <= 12 ? "AM" : "PM";
      return "#{h}:#{m}#{ampm}"
    end
    

    the Time solution:

    def toClock(secs)
      t = Time.gm(2000,1,1) + secs   # date doesn't matter but has to be valid
      return "#{t.strftime("%I:%M%p")}   # copy of your desired format
    end
    

    HTH

提交回复
热议问题