2014-09-19 176 views
0

迄今爲止這是一項相當艱鉅的任務。我想要做的是找出兩個日期範圍之間的日期範圍有多少個月..我知道我現在聽起來像尤達,但讓我更願意告訴你我想要完成的事情。在日期範圍內計算日期範圍中的月份的軌跡

financial_year_2014 = Date.new(2014,6,29)..Date.new(2015,6,30) 
financial_year_2015 = Date.new(2015,6,29)..Date.new(2016,6,30) 

現在我有一個記分卡,每月1點你在financial_year_2014,每月2點,你是在financial_year_2015

所以,如果你的記分卡begin_dateend_date都屬於該financial_year_2014內的獎勵它更容易在那裏你可以做這樣的事情

#Does date fall in range method 
financial_year_2014.include?(scorecard.begin_date..scorecard.end_date) 

,如果它適合在該期限內,然後這些返回true,那麼你可以指望一個月s的:

((scorecard.end_date.year * 12 + scorecard.end_date.month) - (scorecard.begin_date.year * 12 + scorecard.begin_date.month)) * financial_year_2014_points 

但現在我無法得到的是如果一個記分卡BEGIN_DATE和兩個財年之間END_DATE交叉,如果begin_date是五月和end_date是在8月。那麼你將在2014財政年度有2個月,在2015年有2個月。您將在2014年每月獲得1分,2015年每月獲得2分,本例中總共爲6分。

上述示例中的#does date fall in range method即使2個月落入該範圍內也不會通過。任何人都有一個想法,我該如何完成此操作,或者是否有任何處理日期和範圍的gem這個更好。

回答

1

嗯,我不是100%肯定的代碼是如何設置的,但我剛做這樣的事情:

if financial_year_2014.include?(scorecard.begin_date..scorecard.end_date) || financial_year_2015.include?(scorecard.begin_date..scorecard.end_date) 
    #calculate based on 2014/2015 year only 
else 
    #calculate based on split between the years 
    range_one = scorecard.begin_date..Date.new(2015,6,30) 
    range_two = Date.new(2015,6,30)..scorecard.end_date 
    #use new ranges to calculate 
end 
+0

是的,這是我如何使它結構相似,我遇到的問題是找到計分卡可以落入每個範圍的月數的方法 - 如果它確實落在兩個範圍之間financial_year_2014.include?方法將返回false – TheLegend 2014-09-19 14:38:52

+0

@TheLegend我只是編輯我的文章,因爲我真的需要檢查我輸入之前我提交。如果financial_year_2014失敗,並且financial_year_2015失敗,那麼它會被踢進其他的建立2個新的範圍,讓您輕鬆訪問2014個月和2015個月的數量 – MCBama 2014-09-19 14:43:36

2

您可以將日期範圍這樣的內查個月:

require 'date' 
((Date.today - 90)..Date.today).map{|d| [d.month]}.uniq 

要檢查的範圍包括:您可以使用此另一個範圍:

a = ((Date.today - 90)..Date.today) 
b = ((Date.today-10)..(Date.today-5)) 
(a.to_a & b.to_a).empty? # false if includes 

要知道,它的Wi將比較範圍的每個成員。