Time from seconds


#1

Hi

I was just wondering if anyone can think of a simpler way of doing the
following:

def number_to_time(seconds)
seconds = seconds.to_i
if seconds > 1.hours
hours = seconds / 1.hour
hours = “0#{hours}” if hours < 10
seconds = seconds % 1.hour
else
hours = “00”
end
if seconds > 1.minute
minutes = seconds / 1.minute
minutes = “0#{minutes}” if minutes < 10
seconds = (seconds % 1.minute).to_s.sub(’.0’, ‘’)
else
minutes = “00”
end
return “#{hours}:#{minutes}:#{seconds}”
rescue
nil
end

Thanks,
Toby


#2

On 31 Jul 2007, at 16:44, removed_email_address@domain.invalid wrote:

hours = "00"

nil
end

How about

def number_to_time(seconds)
[seconds/3600, seconds/60 % 60, seconds % 60].map{|t| t.to_s.rjust
(2,‘0’)}.join(’:’)
end

Best regards

Peter De Berdt


#3

removed_email_address@domain.invalid wrote:

seconds = seconds % 1.hour

return “#{hours}:#{minutes}:#{seconds}”
rescue
nil
end

How about:

Time.at(seconds).utc.strftime("%H:%M:%S")


Cheers,

  • Jacob A.