2015-04-22 29 views
2

我希望有人能夠幫助我在此leapyear ...包括排除基於沒有fromdate和todate

我有這樣的功能,它是按預期工作。它檢查閏年並相應地花費365或366天。

問題:而不是檢查leapyear的,我要檢查沒有fromdate和todate,如果任何這些日期的開始2月29日,並沒有fromdate和todate之間的差值小於365多隻再加入+1至DAYSINYEAR否則只考慮365天。我將不會有任何在給定的起始時間和結束時間內有兩個閏年的時期。所以我不擔心這種情況。希望很明顯。

getDifference: function(fromdate,toDate) { 
    var now = toDate || new Date(); 
    // days since the date  
    var days = Math.floor((fromdate.getTime() - now.getTime())/1000/60/60/24); 
    var diff = 0; 
    // iterate the years 
    for (var y = now.getFullYear(); y <= fromdate.getFullYear(); y++){ 
    var daysInYear = opc.calculator.leapYear(y) ? 366 : 365; 
    if (days >= daysInYear){ 
     days -= daysInYear; 
     diff++; 
     // increment the age only if there are available enough days for the year. 
    } 
    } 
    return diff; 
} 

回答

2

在你不介意添加庫到你的代碼的情況下,看看:Moment.js

你做這樣的事情:

moment().diff(moment('20140229', 'YYYYMMDD'), 'days'); 
// returns 417 today (2015-04-22) 

// or 

moment('20150422', 'YYYYMMDD').diff(moment('20140229', 'YYYYMMDD'), 'days'); 

這是一個偉大的圖書館工作與時間和日期。

+0

好吧,讓我探索可能性。 –

+0

感謝您分享這個圖書館,我將選擇這個答案作爲答案,因爲我們現在有很多要求是圍繞日期和時間,這個圖書館將是該項目的好資產,謝謝 –