Forum: Ruby on Rails Time from seconds.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2007-07-31 18:44
(Received via mailing list)
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
Peter De Berdt (Guest)
on 2007-07-31 22:08
(Received via mailing list)
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
Jacob A. (Guest)
on 2007-07-31 23:42
(Received via mailing list)
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.
This topic is locked and can not be replied to.