在数据库中存储秒数 - Rails

Store seconds in the database - Rails

我的应用程序中有一个 Timekeeper 模型。它跟踪 started_at 时间和 finished_at 时间。我想计算这两个 datetimes 之间的差异并提取秒数并将该值作为整数存储在数据库中。这是我目前正在使用的东西。

方法:

((timekeeper.started_at - Time.current) * 24 * 60 * 60).to_i

这个 returns 看起来像这样的值:-2336036

上面的两次只相隔12秒,我得到了那个值。我不确定它在说什么。

我的问题的结论是:How can I store seconds in the database, between two datetimes that looks similar to what I'm doing currently?

如果您想求出这 2 次之间的差值,只需做减法即可,因为差值以秒为单位返回。

time.started_at - Time.current

如果你不想要一秒的小数部分

(time.started_at - Time.current).to_i

和绝对值

((time.started_at - Time.current).to_i).abs

在 rails 控制台中尝试以上操作