简体   繁体   English

比较Postgres和Rails中的时间

[英]Comparing times in postgres and Rails

Very simply put, I have a query: 简单地说,我有一个查询:

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

My problem is, I think the time being compared in the database and the last_sync_time_from_client are being compared on a float basis. 我的问题是,我认为正在比较数据库中的时间和last_sync_time_from_client是浮动的。 This always results in the updated_at > last_sync_time_from_client being true even when the time is identical to the second. 即使时间updated_at > last_sync_time_from_client秒,这始终会导致updated_at > last_sync_time_from_client为true。

Ie

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

This means that the times, which are the same down to the second, will return oddities. 这意味着直到第二秒的时间都将返回奇数。 Is there a way to fix this, or should I simply add a second to the last_sync_time_from_client to account for Rails being strange here? 有没有办法解决这个问题,还是我应该在last_sync_time_from_client中添加一秒钟,以解决Rails在这里很奇怪的问题?

Here are three solutions. 这是三个解决方案。 Solution 1 is the best (non-destructive). 解决方案1是最好的(无损)。 Solutions 2 and 3 affect the stored values in database directly, and so choose it at your own risk. 解决方案2和3直接影响数据库中的存储值,因此选择此方法后果自负。

Solution 1 解决方案1

Use 采用

date_trunc('second', updated_at);

instead of updated_at . 而不是updated_at See the answer to "Discard millisecond part from timestamp" for detail. 有关详细信息,请参见“从时间戳中丢弃毫秒部分”的答案

Solution 2 解决方案2

Force Rails always to update the timestamp with the precision of a second, truncating the sub-second part to zero. Force Rails始终以一秒的精度更新时间戳,将亚秒部分截断为零。

See an answer to "Is there a way to change Rails default timestamps to Ymd H:i:s (instead of Ymd H:i:su) or have laravel ignore decimal portion of Ymd H:i:su?" 请参阅“是否有办法将Rails默认时间戳更改为Ymd H:i:s(而不是Ymd H:i:su)或让laravel忽略Ymd H:i:su的小数部分?”的答案。

Solution 3 解决方案3

Make the precision of the updated_at column in the database a second, as opposed to the default sub-second (like a milli-second). 使数据库中的updated_at列的精度为一秒,而不是默认的亚秒(如毫秒)。

See the answers to "how to change rails migration t.timestamps to use timestamp(0) without timezone in postgres" for how to do it with Rails migration. 有关如何使用Rails迁移的信息,请参见“如何将Rails迁移t.timestamps更改为在postgres中使用timestamp(0) without timezone ”的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM