代码之家  ›  专栏  ›  技术社区  ›  Rubioli

Ruby-从给定日期获取过去的x个月

  •  0
  • Rubioli  · 技术社区  · 3 年前

    我如何才能从一个给出日期中获得过去的x个月?

    例如,如果日期是 2023-01-04年 ,我想要过去的3个月 (包括当前日期) ,它会给我一个 array 第页,共页:

    [
    '2023-01-01',
    '2022-12-01',
    '2022-11-01'
    ]
    

    我尝试过:

    current_month = Date.today.month
    3.downto(1).map { |n| Date.parse(DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12]).strftime('%Y-%m-%d') }
    

    当这一年还没有结束的时候,它运行得很好,只给出了捐赠年份的月份,而对于新的一年,它输出的日期完全错误。

    附言:我看到了一些解决方案,但什么都不起作用

    1 回复  |  直到 3 年前
        1
  •  6
  •   Beartech    3 年前

    您可以使用以下方法 beginning_of_month Rails非常容易地处理简单的日期计算:

    编辑:使用OP的原始形式:

    2.downto(0).map {|i| Date.today.beginning_of_month - (i).months}
    

    正如塔德曼所指出的,这更清洁。他们只需要在代码中的其他地方将“我想要三个月”=3-1的逻辑转换为0。

    my_dates = (1..3).map {|i| Date.today.beginning_of_month - (i - 1).months}
    
    #=> [Sun, 01 Jan 2023, Thu, 01 Dec 2022, Tue, 01 Nov 2022]
    

    这个输出看起来很奇怪,因为控制台显示的是日期对象,所以它们的颜色应该与方括号和日期之间的逗号不同。

        2
  •  2
  •   Cary Swoveland    3 年前

    这仅仅实现了@steenslag对这个问题的评论。

    require 'date'
    
    def prev_dates(date_str, nbr_months)
      arr = [DateTime.strptime(date_str[0,7], '%Y-%m')]
      (nbr_months-1).times { arr << (arr.last << 1) }
      arr.map { |date| date.strftime('%Y-%m-%d') }
    end
    
    prev_dates('2023-01-04', 3)
      #=>["2023-01-01", "2022-12-01", "2022-11-01"]
    prev_dates('2023-01-04', 1)
      #=> ["2023-01-01", "2022-12-01", "2022-11-01"]
    

    看见 DateTime::strptime 和 Date#strftime 。