hitsuyashi hitsuyashi - 2 years ago 104
Ruby Question

Display time down to milliseconds in Ruby 1.8.7

I'm trying to get my application to show time down to the milliseconds (e.g. 11:37:53.231), but

in 1.8.7 doesn't seem to have an option for it (http://ruby-doc.org/core-1.8.7/Time.html#method-i-strftime). In Ruby >= 1.9.3, there's the %3N option (http://ruby-doc.org/core-1.9.3/Time.html#method-i-strftime), but it's not in the docs for 1.8.7, and doesn't seem to work either.

This is the output I get in Ruby 1.8.7.

cur_time = Time.now
# => Mon Jun 24 12:43:14 +0900 2013
# => "12:43:14.%3N"

Is there alternative solution? Unfortunately, moving to 1.9.3 isn't an option.

Answer Source

How about something like this:

class Time
  def to_milliseconds
    (self.to_f * 1000.0).to_i


some_time = Time.now
some_time.to_milliseconds # Time in milliseconds. It will be a big number

some_time.strftime("%H:%M:%S.#{some_time.to_milliseconds % 1000}") # Same as some_time.strftime('%H:%M:%S.%3N')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download