midwire
8/19/2014 - 1:21 AM

Convert time (HH:MM:SS) to seconds and back again

Convert time (HH:MM:SS) to seconds and back again

module MidwireCommon

  class TimeTool

    # converts the given time (HH:MM:SS) to seconds
    #
    # +time+ the time-string
    def self.time_to_seconds(time)
      return -1 if time.nil? or time.strip.empty?
      times = time.split(/:/).reverse
      seconds = 0
      for i in (0...times.length)
        seconds += times[i].to_i * (60**i)
      end
      return seconds
    end

    # converts the given seconds into a time string (HH:MM:SS)
    #
    # +seconds+ the seconds to convert
    def self.seconds_to_time(seconds)
      return "unknown" if seconds.nil?
      t = seconds
      time = ""
      2.downto(0) { |i|
        tmp = t / (60**i)
        t = t - tmp * 60**i
        time = time + ":" if not time.empty?
        time = time + ("%02d" % tmp)
      }
      return time
    end
  end

end