如何获取昨日时间的毫秒数?Ruby代码返回0.0问题求助
Ah, I’ve been there before—strftime can be finicky with certain format specifiers depending on your Ruby version. The reason you’re getting 0.0 is that %Q isn’t universally supported across all Ruby environments, or it might not be parsing correctly for your Time object.
Here are a few reliable ways to fix this:
1. Use ActiveSupport’s in_milliseconds (Rails-specific)
Since you’re using Rails (evident from 1.day.ago), ActiveSupport adds a handy method directly to Time objects that does exactly what you need:
yday = 1.day.ago yday.in_milliseconds # => 1522763724000 (example value)
This gives you the precise number of milliseconds since the Unix epoch without any extra math.
2. Ruby-native approach (no Rails dependencies)
If you want a solution that works in plain Ruby:
- To get integer milliseconds (truncates fractional seconds):
yday = 1.day.ago yday.to_i * 1000 # => 1522763724000
- To get rounded milliseconds (includes fractional seconds from the original time):
(yday.to_f * 1000).round # => 1522763724123 (if milliseconds exist in the timestamp)
Why your original code failed
The %Q format specifier is supposed to return milliseconds since epoch, but it’s only supported in Ruby 1.9.2+, and even then, some implementations (like older JRuby versions) might handle it inconsistently. When strftime returned an empty or non-numeric string, converting it to a float with to_f resulted in 0.0.
Give one of the above methods a shot—they should work reliably!
内容的提问来源于stack exchange,提问作者satish

