Search code examples
rubytimeformattingleading-zero

How do I eliminate leading zeroes from my time conversion function?


I'm using Rails 4.2.7. I have this function for converting time in milliseconds to a readable string

  def time_formatted
    Time.at(time_in_ms/1000).utc.strftime("%H:%M:%S")
  end

My question is, if I have something less than an hour, the function returns “00:37:25” or if I have something less than 10 minutes, the function returns “00:07:52”. How do I eliminate leading zeroes from my function?


Solution

  • say you have

    time = "00:37:25"
    

    You can use regex to remove the leading zeroes

    regex = /^(0*:?)*/
    

    Then you can run sub!

    str.sub!(regex, '') #=> 35:25