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

Rails查询中如何将日期字段差值转换为秒数?

解决Rails中计算时间差(秒数)的问题

问题根源

你直接用 end_time_at - start_time_at 时,数据库并没有按时间差逻辑计算,而是把时间字段当作字符串或数值做了减法(比如示例里的 101120 - 101016 = 104),所以得到了错误结果。需要用数据库原生的时间差函数来精准计算秒数。

解决方案

根据你使用的数据库类型,修改查询中的 select 语句:

1. 若使用 PostgreSQL

用 EXTRACT(EPOCH FROM ...) 获取时间差的秒数:

@zones = Zone.where(
  customer: container.customer_id,
  container: container_id,
  start_time_at: start_time..end_time
).select(
  'address',
  'start_time_at',
  'end_time_at',
  'notified_at',
  'EXTRACT(EPOCH FROM (end_time_at - start_time_at)) AS "Time"'
).as_json(except: :id)

2. 若使用 MySQL

用 TIMESTAMPDIFF 函数指定计算秒数:

@zones = Zone.where(
  customer: container.customer_id,
  container: container_id,
  start_time_at: start_time..end_time
).select(
  'address',
  'start_time_at',
  'end_time_at',
  'notified_at',
  'TIMESTAMPDIFF(SECOND, start_time_at, end_time_at) AS "Time"'
).as_json(except: :id)

额外提示

你的代码存在变量大小写不一致问题:定义的是 @Zone,但渲染时用的是 @zone,这会导致返回数据为空,记得统一变量名(建议用小写开头的 @zones,符合Ruby命名规范)。

内容的提问来源于stack exchange,提问作者Memories

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:35:33