2017-06-06 19 views

回答

1

var namedMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; 
 
//Format: yyyy-mm-dd 
 
function stringToDate(datestring) { 
 
    var d = new Date(0); 
 
    d.setHours(2); 
 
    d.setFullYear(parseInt(datestring.substr(0, 4), 10)); 
 
    d.setMonth(parseInt(datestring.substr(5, 2), 10)); 
 
    d.setDate(parseInt(datestring.substr(8, 2), 10)); 
 
    return d; 
 
} 
 

 
function monthsBetween(from, to, cb) { 
 
    if (cb === void 0) { 
 
    cb = function(month) {}; 
 
    } 
 
    //Convert to date objects 
 
    var d1 = stringToDate(from); 
 
    var d2 = stringToDate(to); 
 
    //month counter 
 
    var months = 0; 
 
    //Call callback function with month 
 
    cb(d1.getMonth()); 
 
    //While year or month mismatch, reduce by one day 
 
    while (d2.getFullYear() != d1.getFullYear() || d2.getMonth() != d1.getMonth()) { 
 
    var oldmonth = d1.getMonth(); 
 
    d1 = new Date(d1.getTime() + 86400000); 
 
    //if we enter into new month, add to month counter 
 
    if (oldmonth != d1.getMonth()) { 
 
     //Call callback function with month 
 
     cb(d1.getMonth()); 
 
     months++; 
 
    } 
 
    } 
 
    //return month counter as result 
 
    return months; 
 
} 
 
//test 
 
var d1 = '2014-05-01'; 
 
var d2 = '2017-06-01'; 
 
console.log(monthsBetween(d1, d2, function(month) { 
 
    console.log(namedMonths[month]); 
 
}), "months between:", d1, "and", d2);

編輯1 - 修正了上面的代碼中包含一個回調函數

使用回調「按月」操作的事,喜歡它登錄到控制檯或寫入它到你的文件。

+0

@ Emil.But它只返回總數。 – ArunJaganathan

相關問題