【问题标题】:Ruby Time.now and Other datesRuby Time.now 和其他日期
【发布时间】:2012-11-07 08:32:00
【问题描述】:

我需要在变量中获取三个日期

今天从午夜开始,我有这个

t = Time.now.strftime("%Y-%m-%d 00:00:01") # 2012-11-19 00:00:01

昨天从午夜开始(即 00:00:00 到 23:59:59)

y1 = 2012-11-18 00:00:01
y2 = 2012-11-19 23:59:59

特别是我需要创建为字符串以在 gem 中使用的 y1 和 y2 变量。作为 ruby​​ 的新手,我有点困惑,因为 Time.yesterday 似乎没有做我需要的事情

编辑

为此请务必包括

需要'active_support/all'

并确保为您的应用程序捆绑 gem。

使用:

@current   = (Time.now).beginning_of_day.utc.strftime("%Y-%m-%d")
@yesterday = (Time.now - 1.day).beginning_of_day.utc.strftime("%Y-%m-%d")
@everything = (Time.now - 2.day).end_of_day.utc.strftime("%Y-%m-%d")

【问题讨论】:

    标签: ruby-on-rails ruby strftime


    【解决方案1】:

    你可以的,

     t=Time.now
     y1=t-1.day
     y2=t+1.day
    

    【讨论】:

      【解决方案2】:
      t = Time.now
      t - 1.day # => yesterday
      t + 1.day # => tomorrow
      

      【讨论】:

      • 我收到此错误<top (required)>': undefined method -' for "2012-11-19":String (NoMethodError)
      • 你必须添加或减去时间对象,现在是你用 strftime 得到的字符串。
      【解决方案3】:

      先将 t 转换为日期,

      t = t.to_date
      
      t - 1.day # => yesterday
      t + 1.day # => tomorrow
      

      【讨论】:

        【解决方案4】:

        由于您正在运行 Rails,因此可以从 ActiveSupport 获得帮助

        1.day.ago.midnight
        Time.new.beginning_of_day
        

        您还应该考虑不使用2012-11-19 00:00:012012-11-19 23:59:59。 相反,您可以使用 00:00:00 并根据您想要实现的目标与 >= 或 2012-11-19 00:00:00 到 2012-11-19 23:59:59 就可以了。

        【讨论】:

          猜你喜欢
          • 2019-07-10
          • 2013-03-09
          • 1970-01-01
          • 2019-03-03
          • 1970-01-01
          • 2018-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多