Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display time down to milliseconds in Ruby 1.8.7

Tags:

time

ruby

I'm trying to get my application to show time down to the milliseconds (e.g. 11:37:53.231), but strftime 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
cur_time.strftime('%H:%M:%S.%3N')
# => "12:43:14.%3N"

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

like image 708
sheepbrew Avatar asked Jun 24 '13 04:06

sheepbrew


2 Answers

I think you might be looking for "%L", which will give you milliseconds in three digits.

cur_time.strftime('%H:%M:%S.%L')     #=> "12:34:56.789"

However, I'm not sure if this is supported in older versions of Ruby.

like image 182
Jay Kay Avatar answered Oct 15 '22 04:10

Jay Kay


How about something like this:

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

Then

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')
like image 22
nicosantangelo Avatar answered Oct 15 '22 04:10

nicosantangelo