【问题标题】:Ruby(/Rails) dates - bi-weekly and quarterly DateTime rangesRuby(/Rails) 日期 - 双周和季度 DateTime 范围
【发布时间】:2018-08-19 08:20:33
【问题描述】:

我正在尝试针对特定时期进行报告,支持的时期是:

  • “今天”:start = DateTime.now.beginning_of_day; end = start.end_of_day
  • “本周”:start = DateTime.now.beginning_of_week; end = start.end_of_week
  • 这两周”(上半月或下半月,相对于DateTime.now 的当前日期)
    • 非常重要的是要确保月份是平分的,不使用cweek;第一个双周的开始应该是一个月的第一天,第二个双周的结束应该是这个月的最后一个。两者之间的划分日期应该是当月的总天数除以 2,四舍五入(即如果有 31 天,则第二个双周将从 15 日开始,而不是 14 日开始)。
  • “本月”:start = DateTime.now.beginning_of_month; end = start.end_of_month
  • “上个月”:start = (DateTime.now - 1.month).beginning_of_month; end = start.end_of_month
  • 本季度”:一年中四个 3 个月期间中的一个,即季度。例如:从 1999 年 1 月 1 日到 1999 年 3 月 31 日或从 2000 年 10 月 1 日到 2000 年 12 月 31 日。
  • “今年”=start = DateTime.now.beginning_of_year --> end = start.end_of_year

我在根据当前日期计算粗体日期范围时遇到问题(假设DateTime.now)。

如何计算相对于当前日期DateTime.now 的双周和季度周期?

预期输出

日期为 2018 年 5 月 7 日(2018 年 5 月 7 日):

  • 这两周”应该是5/1/20185/15/2018的时间段
  • 本季度”应该是4/1/20186/30/2018的时期

对于 2020 年 2 月 29 日(2020 年 2 月 29 日)这一天,闰年:

  • 这两周”应该是2/15/20182/29/2018的时间段
  • 本季度”应该是1/1/20183/31/2018的时期

【问题讨论】:

    标签: ruby-on-rails ruby date datetime


    【解决方案1】:

    这个呢:

    这两周:

    def bi_week_limits_for(date)
      days_in_month = Time.days_in_month(date.month, date.year)
      # this will round down. 30/31-day months will output 15. 28 / 29-day will output 14. Adjust as per your requirements
      middle_day    = days_in_month / 2
      if date.day <= middle_day
        [date.beginning_of_month, date.change(day: middle_day)]
      else 
        [date.change(day: middle_day + 1), date.end_of_month]
      end 
    end
    

    在我的控制台中:

    pry(main)> bi_week_limits_for Date.parse('29/2/2020')
    => [Sat, 15 Feb 2020, Sat, 29 Feb 2020]
    pry(main)> bi_week_limits_for Date.parse('7/5/2018')
    => [Tue, 01 May 2018, Tue, 15 May 2018]
    

    本季度:

    def bi_week_limits_for(date)
      [date.beginning_of_quarter, date.end_of_quarter]
    end
    

    在我的控制台中

    pry(main)> date = Date.parse('7/5/2018')
    => Mon, 07 May 2018
    pry(main)> quarter_limits_for date
    => [Sun, 01 Apr 2018, Sat, 30 Jun 2018]
    
    pry(main)> date = Date.parse '29/2/2020'
    => Sat, 29 Feb 2020
    pry(main)> quarter_limits_for date
    => [Wed, 01 Jan 2020, Tue, 31 Mar 2020]
    

    参考:https://apidock.com/rails/DateAndTime/Calculations/beginning_of_quarter

    【讨论】:

    • 非常感谢您的快速回答!非常有用的东西 - 我无法围绕双周逻辑来思考,所以非常感谢。我也觉得自己像个白痴,因为在搜索文档时,我没有看到任何与季度日期计算相关的内容。我怎么会错过?!一切都像魅力一样运作,谢谢!
    • 很高兴为您提供帮助 :) 玩日期比较棘手,因为它最初出现......我们甚至没有谈论时区! :P
    • 好点!幸运的是,至少在接下来的几年里,我的系统将处于一个时区。到那时,我将不得不重新审视双周计算来解释它们。但是现在,YAGNI(你不需要它):)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多