【问题标题】:Display time remaining with distance_of_time_in_words用 distance_of_time_in_words 显示剩余时间
【发布时间】:2016-03-15 06:03:42
【问题描述】:

所以我希望项目在 7 天后显示在 Items 上,该项目将被删除。我试过了

 <%= distance_of_time_in_words(item.created_at, item.created_at + 7.days) %> 

但我得到的只是所有项目的“7 天”。任何人都可以简单地了解这个辅助方法是如何工作的吗?

【问题讨论】:

  • 所以你需要的是与当前时间的差异。所以你应该这样做:distance_of_time_in_words(Time.now, item.created_at + 7.days)。如果您尝试执行2 - (2 + 7),它将始终只返回-7,并且永远不会改变。
  • 感谢小类比帮助,非常感谢!

标签: ruby-on-rails ruby helpermethods


【解决方案1】:

让我们看看the documentation 看看distance_of_time_in_words 做了什么:

distance_of_time_in_words(from_time, to_time = 0, options = {})
以秒为单位报告两个 Time、Date 或 DateTime 对象或整数之间的大致时间距离。

所以它会报告第一个参数和第二个参数的时间差。现在,你正在做:

distance_of_time_in_words(item.created_at, item.created_at + 7.days)

item.created_atitem.created_at 之间的区别加上 7 天总是 ... 7 天 ;-)

我认为这是 7 天后总会被删除的内容?在这种情况下,您想要的是当前日期和创建日期之间的差加上 7 天,您可以使用:

distance_of_time_in_words(Time.now, item.created_at + 7.days)

【讨论】:

  • 是的,这就是我想要的,谢谢。处理日期对我来说有点困难,所以这种方法把我的头发都弄乱了。谢谢你的解释:)
  • @MiguelAngelQuintana 是的,约会可能很尴尬。但它们只是数字。许多计算机将日期存储为自 1970 年 1 月 1 日以来的秒数(当前为 1458023724),当您说+ 7.days 时,您实际上只是在做一个简单的加法:1458023724 + 86400 * 7(一天有 86400 秒,这是一个有用的数字来记住),仅此而已。将其显示为“Tue Mar 15 07:36:24 CET 2016”或“5 days and 6 hours”对于我们这些可怜的人类来说实际上只是一个格式化的东西,就像将125秒显示为2:0553.31一样€53,31...
猜你喜欢
  • 2021-12-29
  • 2020-06-27
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多