

ruby on rails - How would I format a time string?


Here's the string I've got: 00:03:30.877615

That's hours, minutes and seconds.

What I want to do is format that same string as: 3:30

I basically want minutes (without the leading zero) and whole seconds.

The string will mostly be the same, but the length of the decimal places could change.


You have a couple of options here. If you know your starting string is always going to be the same length/structure you could do a simple string transform:

start_time = '00:03:30.877615'
mins_and_secs = start_time[3..7]
mins_and_secs = mins_and_secs[1..-1] if mins_and_secs[0] == '0'

This is going to be the fastest option. If you're expecting more variation you could actually create a Time object and then use #strftime.


The "-" takes out the leading zero in the minutes.

>> require 'time'
=> []
>> t = Time.parse('00:03:30.877615')
=> 2012-01-12 00:03:30 -0800
>> t.strftime("%-m:%S")
=> "1:30"

can you rely on that time format? if so, I might just use a regular expression and pull out the bits I want:

reg = /\d\d:(\d\d):(\d\d).*/
if m = reg.match(s)
  "#{ m[1].to_i }:#{ m[2] }"