2010-09-21 135 views
3

我正在尋找一個js(或jQuery)函數,其中我傳遞一個開始日期和結束日期,並且該函數返回每個日期的包含列表(數組或對象)該範圍。使用javascript獲取在一個範圍內的日期列表

例如,如果我通過該功能的日期對象2010-08-31和2010-09-02,則該函數將返回: 2010-08-31 2010-09-01 2010- 09-02

任何人都有一個功能,這樣做或知道一個jQuery插件,將包括此功能?

回答

4

這聽起來像你可能想使用Datejs。這是非常棒的。


如果使用Datejs,這裏是你如何能做到這一點:

function expandRange(start, end) // start and end are your two Date inputs 
{ 
    var range; 
    if (start.isBefore(end)) 
    { 
     start = start.clone(); 
     range = []; 

     while (!start.same().day(end)) 
     { 
      range.push(start.clone()); 
      start.addDays(1); 
     } 
     range.push(end.clone()); 

     return range; 
    } 
    else 
    { 
     // arguments were passed in wrong order 
     return expandRange(end, start); 
    } 
} 

前。對我來說:

expandRange(new Date('2010-08-31'), new Date('2010-09-02')); 

返回與3日期對象的數組:

[Tue Aug 31 2010 00:00:00 GMT-0400 (Eastern Daylight Time), 
Wed Sep 01 2010 00:00:00 GMT-0400 (Eastern Daylight Time), 
Thu Sep 02 2010 00:00:00 GMT-0400 (Eastern Daylight Time)] 
1

沒有預先定義的方法,我知道,但你可以實現它想:

function DatesInRange(dStrStart, dStrEnd) { 
    var dStart = new Date(dStrStart); 
    var dEnd = new Date(dStrEnd); 

    var aDates = []; 
    aDates.push(dStart); 

    if(dStart <= dEnd) { 
     for(var d = dStart; d <= dEnd; d.setDate(d.getDate() + 1)) { 
      aDates.push(d); 
     } 
    } 

    return aDates; 
} 

你必須添加輸入清理/錯誤檢查(確保日期字符串解析爲實際日期等)。