Dave
Dave

Reputation: 19320

How do I display fractions of a second in my time formatting function?

I'm using Rails 5. I have a method that is supposed to help display a duraiton in milliseconds in a more readable format (hours:minutes:seconds) ...

  def time_formatted time_in_ms 
    regex = /^(0*:?)*0*/ 
    Time.at(time_in_ms/1000).utc.strftime("%H:%M:%S").sub!(regex, '') 
  end

This works basically fine, but it doesn't work completely accurately when the time in milliseconds contains fractions of a second. That is, if the time in milliseconds is

2486300

The above displays

41:26

but really it should display

41:26.3

How can I adjust my function so it will also display fractions of a second, assuming there are any?

Upvotes: 1

Views: 1082

Answers (1)

Sagar Pandya
Sagar Pandya

Reputation: 9508

  • For accuracy make sure you're returning a float (I've used to_f to do this).
  • Append the argument to strftime with ".%1N" for 1-digit milliseconds.
def time_formatted time_in_ms
  regex = /^(0*:?)*0*/ 
  Time.at(time_in_ms.to_f/1000).utc.strftime("%H:%M:%S.%1N").sub!(regex, '') 
end

time_formatted 2486300
#=> "41:26.3"

For more information see Time#strftime in the official Ruby documentation.

Upvotes: 2

Related Questions