【问题标题】:How can I find the dates for the same week a year ago?如何找到一年前同一周的日期?
【发布时间】:2010-12-01 21:45:12
【问题描述】:

这是一周的示例,从周日到周六:

11/21/2010 - 11/27/2010

我想查找周日至周六同一周的日期,仅适用于去年。

【问题讨论】:

    标签: ruby datetime date


    【解决方案1】:
    require 'date' # Included in Ruby's standard library, no gem needed
    now = Date.today
    before = Date.civil( now.year-1, now.month, now.day )
    sunday = Date.commercial( before.year, before.cweek, 1 ) - 1 # Day 1 is Monday
    this_week_last_year = sunday..(sunday+6)
    

    编辑:虽然Date.commercial 很酷,但它不是必需的。以下是查找一周开始的星期日的更简单方法:

    require 'date'
    now    = Date.today
    before = Date.civil( now.year-1, now.month, now.day )
    sunday = before - before.wday
    

    【讨论】:

      【解决方案2】:
      >> 1.year.ago.beginning_of_week.to_date
      Mon, 30 Nov 2009
      >> 1.year.ago.end_of_week.to_date
      Sun, 06 Dec 2009
      

      【讨论】:

        【解决方案3】:
        require 'chronic'
        Chronic.parse '1 year ago'
        # => 2009-12-01 14:05:39 -0800
        

        Chronic 是一个非常可爱的 ruby​​gem,它可以处理一系列事情,包括适应您的特定要求。

        【讨论】:

          【解决方案4】:

          试试这个:

          require 'active_support/all'
          today = Time.now #=> 2010-12-01 14:58:36 -0700
          sunday = (today - today.wday.days).beginning_of_day #=> 2010-11-28 00:00:00 -0700
          saturday = sunday + 6.days #=> 2010-12-04 00:00:00 -0700
          sunday.wday #=> 0
          saturday.wday #=> 6
          
          sunday - 1.year #=> 2009-11-28 00:00:00 -0700
          sunday.prev_year #=> 2009-11-28 00:00:00 -0700
          saturday - 1.year #=> 2009-12-04 00:00:00 -0700
          saturday.prev_year #=> 2009-12-04 00:00:00 -0700
          

          你也可以算出这两天的哪一周,然后减去365.days

          ActiveSupport 实际上在 Rails 3 中被分割成更细的粒度,所以如果你不想要的话,你不必加载整个套件。我这样做是为了简单。更多信息请访问ActiveSupport Core Extensions page

          或者,你可以通过字符串解析变得不稳定:

          require 'chronic'
          Chronic.parse('1 year ago last sunday') #=> 2009-11-28 12:00:00 -0700
          Chronic.parse('1 year ago next saturday') #=> 2009-12-04 12:00:00 -0700
          

          我喜欢 Chronic,而且,对于这种解析,我认为这是一个不错的解决方案,因为字符串是您要创建的东西,而不是用户,因此您的代码因无法解析的字符串而崩溃的可能性较小。我不确定是否会因为解析而降低速度,因此如果解析将处于循环状态,则可能需要一些基准测试。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-01-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多