【问题标题】:Comparing times in postgres and Rails比较 postgres 和 Rails 中的时间
【发布时间】:2019-04-07 11:07:16
【问题描述】:

很简单,我有一个疑问:

@current_user.items.where('updated_at > ? AND updated_at < ?', last_sync_time_from_client, current_time)

我的问题是,我认为在数据库中比较的时间和last_sync_time_from_client 是在浮动基础上进行比较的。这总是导致updated_at &gt; last_sync_time_from_client 为真,即使时间与秒相同。

(db item)updated_at.to_f # 1541246811.022979
last_sync_time.to_f # 1541246811.0

这意味着直到秒都相同的时间将返回异常值。有没有办法解决这个问题,或者我应该简单地在 last_sync_time_from_client 中添加一秒钟以说明 Rails 在这里很奇怪?

【问题讨论】:

  • 这里没有什么奇怪的。秒不是最小的时间单位。如果您的逻辑要求,您可以truncate the date to the second,但我不明白您为什么应该这样做。您不想返回在last_sync_time_from_client 之后 1 毫秒更新的项目吗?您是否还期望updated_at 会在未来出现?如果不是,那么确保它小于 current_time 是没有必要的

标签: ruby-on-rails postgresql parsing time comparison


【解决方案1】:

这里有三个解决方案。解决方案 1 是最好的(非破坏性的)。解决方案 2 和 3 直接影响数据库中的存储值,因此选择它需要您自担风险。

解决方案 1

使用

date_trunc('second', updated_at);

而不是updated_at。 详情请见the answer to "Discard millisecond part from timestamp"

解决方案 2

强制 Rails 始终以秒的精度更新时间戳,将亚秒部分截断为零。

an answer to "Is there a way to change Rails default timestamps to Y-m-d H:i:s (instead of Y-m-d H:i:s.u) or have laravel ignore decimal portion of Y-m-d H:i:s.u?"

解决方案 3

将数据库中updated_at 列的精度设为一秒,而不是默认的亚秒(如毫秒)。

请参阅the answers to "how to change rails migration t.timestamps to use timestamp(0) without timezone in postgres",了解如何使用 Rails 迁移。

【讨论】:

  • 谢谢。我意识到我自己的代码存在问题 - 我应该首先保持毫秒,但我接受了这个答案,因为它确实提供了丰富的信息。
猜你喜欢
  • 2016-12-01
  • 2021-12-06
  • 1970-01-01
  • 2012-07-08
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多