简体   繁体   中英

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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