简体   繁体   English

Ruby on Rails-时间条件

[英]Ruby on Rails- Time Condition

I want to compare the current time with submission with Datetime stamp to setup a controller which only shows submission of a specific time. 我想将当前时间与带有Datetime戳的提交进行比较,以设置仅显示特定时间提交的控制器。 Such as posts done in past hour, day or week. 例如过去一小时,一天或一周内发布的帖子。

So I don't get how to access current time. 所以我不知道如何访问当前时间。 Does it need to be part of database? 它需要成为数据库的一部分吗? How can it be defined and how to compare it which post submissions? 如何定义它以及如何比较哪些帖子?

From the below query you will get the posts that got created one hours ago. 从以下查询中,您将获得一小时前创建的帖子。

now = Time.now

@posts= Post.where(created_at: (now - 1.hours)..now)

To get posts created one week ago 获取一周前创建的帖子

@posts = Post.where("created_at > ?", Time.now - 7.days)

To add to the earlier answer 添加到先前的答案

For posts this week 对于本周的帖子

@posts = Post.where("created_at > ?", Time.now.beginning_of_week)

For posts this month: 对于本月的帖子:

@posts = Post.where("created_at > ?", Time.now.beginning_of_month)

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

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