代码之家  ›  专栏  ›  技术社区  ›  Vincent

Ruby/Rails-如何将秒转换为时间?

  •  10
  • Vincent  · 技术社区  · 14 年前

    我需要执行以下转换:

    0     -> 12.00AM
    1800  -> 12.30AM
    3600  -> 01.00AM
    ...
    82800 -> 11.00PM
    84600 -> 11.30PM
    

    我想到了这个:

    (0..84600).step(1800){|n| puts "#{n.to_s} #{Time.at(n).strftime("%I:%M%p")}"}
    

    这给了我错误的时间,因为时间。at(n)期望n是从epoch开始的秒数:

    0     -> 07:00PM
    1800  -> 07:30PM
    3600  -> 08:00PM
    ...
    82800 -> 06:00PM
    84600 -> 06:30PM
    

    对于这种转换,什么是最理想的、与时区无关的解决方案?

    3 回复  |  直到 12 年前
        1
  •  33
  •   Mark Thomas    14 年前

    最简单的一行程序只会忽略日期:

    Time.at(82800).utc.strftime("%I:%M%p")
    
    #-> "11:00PM"
    
        2
  •  3
  •   Stephan Wehner    14 年前

    不确定这是否比

    (Time.local(1,1,1) + 82800).strftime("%I:%M%p")
    
    
    def hour_minutes(seconds)
      Time.at(seconds).utc.strftime("%I:%M%p")
    end
    
    
    irb(main):022:0> [0, 1800, 3600, 82800, 84600].each { |s| puts "#{s} -> #{hour_minutes(s)}"}
    0 -> 12:00AM
    1800 -> 12:30AM
    3600 -> 01:00AM
    82800 -> 11:00PM
    84600 -> 11:30PM
    

    斯蒂芬

        3
  •  2
  •   Michael Durrant    12 年前

    两个提议:

    精心设计的DIY解决方案:

    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
    

    时间解决方案:

    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
    

    高温高压