在Ruby 1.8.7中显示时间缩短到毫秒

hit*_*shi 9 ruby time

我试图让我的应用程序显示时间到毫秒(例如11:37:53.231),但strftime在1.8.7似乎没有它的选项(http://ruby-doc.org/ core-1.8.7/Time.html#method-i-strftime).在Ruby> = 1.9.3中,有%3N选项(http://ruby-doc.org/core-1.9.3/Time.html#method-i-strftime),但它不在1.8的文档中. 7,似乎也没有用.

这是我在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"
Run Code Online (Sandbox Code Playgroud)

有替代解决方案吗?不幸的是,转向1.9.3不是一种选择.

小智 25

我想你可能正在寻找"%L",这将给你三位数的毫秒数.

cur_time.strftime('%H:%M:%S.%L')     #=> "12:34:56.789"
Run Code Online (Sandbox Code Playgroud)

但是,我不确定旧版本的Ruby是否支持这种功能.


nic*_*elo 9

这样的事情怎么样:

class Time
  def to_milliseconds
    (self.to_f * 1000.0).to_i
  end
end
Run Code Online (Sandbox Code Playgroud)

然后

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')
Run Code Online (Sandbox Code Playgroud)