【问题标题】:How to know if a date is the previous month or earlier?如何知道日期是上个月还是更早?
【发布时间】:2017-08-31 07:55:12
【问题描述】:

我正在寻找一些开始向我的客户收费的条件。 每次我的客户与我签订合同时,我都会在属性 start_billing_at 中初始化一个日期。我现在想知道 start_billing_at 属性是否已在上个月初始化。希望我的问题现在更清楚了

谢谢帮助

编辑

我必须知道我的日期是否在上个月的第一天和最后一天之间

【问题讨论】:

  • 你的问题不清楚,能否补充一下,以便我们理解和帮助你

标签: ruby-on-rails ruby date datetime


【解决方案1】:

减去两个日期并在其上调用to_i 会给你天数的差异,你可以打开它:

if (Date.today - other_date).to_i < 30
  # less than a month
else
  # more than a month
end

当然,这并不完全遵循月份,但对于我的用例来说,它通常已经足够好了。

另一种选择是:

if date_to_check > Date.today.last_month
  # within the last month
end

或检查是否包含在上个月的日期范围内:

last_month = Date.today.last_month
(last_month.beginning_of_month..last_month.end_of_month).cover?(date_to_check)

【讨论】:

  • 这可能是一个解决方案,但是 31 天的 mont 呢?
  • 第二种方法更聪明一些,即Date.new(2017, 3, 31).last_month #=&gt; Tue, 28 Feb 2017(它是28号,而不是31号)。我再给你添加一个选项,等待编辑。
【解决方案2】:
%w|2017-07-01 2017-06-01|.map do |d|
  (Date.today.month - Date.parse(d).month) % 12 == 1
end
#⇒ [true, false]

【讨论】:

    【解决方案3】:

    这是我的解决方案,基于 Michael kohl 解决方案

    def calcul_bill(date)
      if Time.zone.today.last_month.strftime('%b, %Y') == date.strftime('%b, %Y')
        #Do actions
      else
        #Do other actions
      end
    end
    

    我的日期格式是“2017 年 8 月 30 日星期三”,所以我只比较月份和年份

    【讨论】:

      【解决方案4】:

      我相信我会选择:

      start_billing_at.beginning_of_month == Date.today.last_month.beginning_of_month
      

      通过改进,您可以定义一个日期方法,允许您:

      start_billing_at.last_month?
      

      所以:

      module BillingDateExtensions
        refine Date do
          def last_month?
            self.beginning_of_month == Date.today.last_month.beginning_of_month
          end
        end
      end
      

      ...您可以将其混入您需要的日期:

      using BillingDateExtensions
      

      【讨论】:

        猜你喜欢
        • 2017-10-31
        • 1970-01-01
        • 2023-01-23
        • 2014-08-25
        • 1970-01-01
        • 2021-03-04
        • 2011-07-05
        • 2014-04-13
        • 2016-06-29
        相关资源
        最近更新 更多