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

Neo4j中如何获取duration.between返回值包含天数的总分钟数

Neo4j Cypher 获取duration总分钟/小时数方案

问题原因

duration.between()返回的时长实例的.minutes、.hours属性仅返回对应时间单位的余数,不会自动折算年、月、日等上层单位的时长,因此无法直接得到全量折算后的总分钟/小时数。

解决方案

无需手动编写多单位换算公式,两种内置方案均可实现需求:

  • 方案1:使用duration内置方法折算
    duration实例内置的toSeconds()方法会自动将所有时间单位(年、月、日、小时、分、秒)折算为总秒数,再按需求转换为对应单位即可:
    • 总分钟数:toInteger(duration.between(开始时间, 结束时间).toSeconds() / 60)
    • 总小时数:toInteger(duration.between(开始时间, 结束时间).toSeconds() / 3600)
      如需保留小数精度,去掉外层toInteger()即可。
  • 方案2:直接通过时间戳计算
    直接取两个datetime的秒级Unix时间戳相减,再折算为对应单位,写法更简洁:
    • 总分钟数:toInteger((结束时间.epochSeconds - 开始时间.epochSeconds) / 60)

修正后的查询示例

MATCH (yv:YoutubeVideo)
WHERE datetime(yv.publishedAt) >= datetime('2021-11-16T12:05:47.897962')
WITH 
  yv,
  datetime('2021-11-16T12:05:47.897962') as startDate,
  yv.publishedAt as expectedDate,
  // 计算全量折算的总分钟数
  toInteger(duration.between(startDate, datetime(yv.publishedAt)).toSeconds() / 60) as totalMinutes
RETURN 
  duration.between(startDate, datetime(yv.publishedAt)) as duration, 
  startDate,
  expectedDate + duration({minutes:totalMinutes}) as expectedRes,
  startDate + duration({minutes:totalMinutes}) as resultDate
LIMIT 1

上述代码对于3天4小时20分钟的时长,计算得到的totalMinutes值为4580,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:36:04