2017-08-31 51 views
0

我正在尋找一些條件來開始爲我的客戶開帳單。 每當我的客戶與我簽訂合同時,我都會在屬性start_billing_at中初始化一個日期。我現在想知道,如果start_billing_at屬性在上個月已經初始化。希望我的問題是更清晰現在如何知道日期是上個月還是之前?

THX的幫助

編輯

心中已經認識了,如果我的日期是第一個和上月的最後一天

+0

你的問題是不明確的,你可以請添加更多這樣我們就可以理解和幫助你 –

回答

0

這裏是我的解決方案的基礎上,邁克爾·科爾的解決方案

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日」是這樣的情況,所以我只是比較年份和月份

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) 
+0

這可能是一個解決方案是考慮,但對於31天蒙? – Che

+0

第二種方法比較智能一點,即'Date.new(2017,3,31).last_month#=> 2017年2月28日星期二「(它到達第28位,而不是第31位)。我會爲你添加一個選項,等待編輯。 –

0
%w|2017-07-01 2017-06-01|.map do |d| 
    (Date.today.month - Date.parse(d).month) % 12 == 1 
end 
#⇒ [true, false] 
0

,我相信我會去:

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 
相關問題