我正在寻找一些条件来开始为我的客户开帐单。 每当我的客户与我签订合同时,我都会在属性start_billing_at中初始化一个日期。我现在想知道,如果start_billing_at属性在上个月已经初始化。希望我的问题是更清晰现在如何知道日期是上个月还是之前?
THX的帮助
编辑
心中已经认识了,如果我的日期是第一个和上月的最后一天
我正在寻找一些条件来开始为我的客户开帐单。 每当我的客户与我签订合同时,我都会在属性start_billing_at中初始化一个日期。我现在想知道,如果start_billing_at属性在上个月已经初始化。希望我的问题是更清晰现在如何知道日期是上个月还是之前?
THX的帮助
编辑
心中已经认识了,如果我的日期是第一个和上月的最后一天
这里是我的解决方案的基础上,迈克尔·科尔的解决方案
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日”是这样的情况,所以我只是比较年份和月份
减法之间两个日期,并呼吁它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天蒙? – Che
第二种方法比较智能一点,即'Date.new(2017,3,31).last_month#=> 2017年2月28日星期二“(它到达第28位,而不是第31位)。我会为你添加一个选项,等待编辑。 –
%w|2017-07-01 2017-06-01|.map do |d|
(Date.today.month - Date.parse(d).month) % 12 == 1
end
#⇒ [true, false]
,我相信我会去:
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
你的问题是不明确的,你可以请添加更多这样我们就可以理解和帮助你 –