【问题标题】:Ruby on Rails- Time ConditionRuby on Rails - 时间条件
【发布时间】:2017-03-20 11:44:19
【问题描述】:

我想将当前时间与提交日期时间戳进行比较,以设置一个仅显示特定时间提交的控制器。例如过去一小时、一天或一周内完成的帖子。

所以我不知道如何访问当前时间。它需要成为数据库的一部分吗?它如何定义以及如何比较它提交的哪些帖子?

【问题讨论】:

  • Time.now?你也可以使用1.day.ago等,如果你想比较,只需使用“>”
  • 您尝试了什么,收到了什么?

标签: ruby-on-rails datetime


【解决方案1】:

添加到较早的答案

本周的帖子

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

对于本月的帖子:

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

【讨论】:

    【解决方案2】:

    从以下查询中,您将获得一小时前创建的帖子。

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

    获取一周前创建的帖子

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多