【问题标题】:Get the days remaining from a methods rails从方法轨中获取剩余天数
【发布时间】:2017-03-23 20:29:14
【问题描述】:

我有一个标准DateTime 数据类型的starts_at 属性。我想利用这段时间和当前时间来想出距离活动还剩多少天的3。这是我目前的方法

def days_remaining
  (Date.parse(starts_at) - Date.current).to_i
end

但这给了我这个错误no implicit conversion of ActiveSupport::TimeWithZone into String

这看起来很简单,但我似乎无法弄清楚。

【问题讨论】:

    标签: ruby-on-rails ruby time


    【解决方案1】:

    Date.parse 期待 String 参数,但 starts_atDateTimeto_date 方法会将日期时间转换为日期。

    def days_remaining
      (starts_at.to_date - Date.current).to_i
    end
    

    不过,我认为这不是 100% 正确的方法来查找剩余天数。

    【讨论】:

      【解决方案2】:

      Rails 有distance_of_time_in_words 方法可以用于这种事情。还有 dotiw gem 提供更多的输出自定义:

      distance_of_time_in_words(Time.now, 2.weeks.from_now, only: :days)
      

      【讨论】:

        【解决方案3】:
        def days_remaining
          (starts_at.to_date...Date.current).to_a.count
        end
        

        这可能是您需要的。创建一个日期范围,转换为数组,每个条目是一天,然后计算那些

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-11
          • 1970-01-01
          • 1970-01-01
          • 2012-05-26
          • 2017-06-18
          • 1970-01-01
          相关资源
          最近更新 更多