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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With