【问题标题】:Ruby Year-Month-Date of last SundayRuby 上周日的年月日
【发布时间】:2014-02-19 00:58:28
【问题描述】:

我需要以2014-01-20的格式计算最后两个星期日。

所以,last_sunday = 2014-01-20most_recent_sunday = 2014-01-26

我正在使用 Rails 4.0 和 Ruby 2.0。我怎样才能得到这些日期?

【问题讨论】:

    标签: ruby-on-rails ruby time


    【解决方案1】:
    [11] pry(main)> last_sunday = Time.now - (Time.now.wday + 7) * 86400
    => 2014-01-19 17:17:19 -0600
    [12] pry(main)> most_recent_sunday = Time.now - (Time.now.wday) * 86400
    => 2014-01-26 17:18:03 -0600
    

    【讨论】:

      【解决方案2】:

      我建议你看看chronic gem

      require 'chronic'
      Chronic.parse("last sunday")
      => 2014-01-26 12:00:00 +0200
      

      您还可以使用 rail 的 active_support 从上面计算的日期中减去 7.days =)

      【讨论】:

        【解决方案3】:

        在轨道 4 中:

        most_recent_sunday = Time.now.sunday.to_s
        
        last_sunday =        Time.now.last_week.sunday.to_s
        

        要得到你想要的格式:

        DateTime.parse(most_recent_sunday).strftime("%Y-%m-%d")
        

        http://apidock.com/rails/v4.0.2/DateAndTime/Calculations/sunday http://apidock.com/rails/v4.0.2/DateAndTime/Calculations/last_week

        【讨论】:

        • 感谢您的提示 - 在 TinMan 的回答中有一些有用的信息:stackoverflow.com/questions/279769/… 实际上,我必须在 most_recent_sunday 上附加一个 .to_s 方法才能正确解析,并包括.strftime 方法中的破折号。此外,Time.now.sunday 实际上返回这个即将到来的星期日,而不是最后一个星期日。不过感谢您的帮助,让我足够接近以弄清楚。
        【解决方案4】:

        纯 Ruby 解决方案:

        require 'date'
        
        last_two_weeks   = (Date.today-13)..Date.today
        last_two_sundays = last_two_weeks.select &:sunday?
        
        puts last_two_sundays #=> 2014-01-19, 2014-01-26
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-08
          相关资源
          最近更新 更多