You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取昨日时间的毫秒数?Ruby代码返回0.0问题求助

How to Get Yesterday's Time in Milliseconds in Rails

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:50:17