1

我正在寻找一种简单的方法来获取给定年份中所有日期的字符串数组。就像是:

function getDates( year ) {

    // algorithm...

    return dates;

}

它返回一个数组,如:

    getDates( 2013 ) = {"01/01/2013", "01/02/2013", ... , "12/31/2013"} 

有闰年之类的,所以我宁愿不自己编写代码来重新创建轮子,所以:
问:有没有 JavaScript 插件可以做到这一点?

我知道 Jquery Datepicker,但是在阅读了文档之后,我认为它不会起作用。

4

2 回答 2

3

它可以很简单

var date = new Date(2013, 0, 1);
var end =  new Date(date);
end.setFullYear(end.getFullYear() + 1);
var array = [];
while(date < end){
    array.push(date);
    date.setDate(date.getDate() + 1)
}
于 2013-10-18T07:30:35.537 回答
1
Date.prototype.getDaysInMonth = function(month){
    var date = new Date(this.getFullYear(), month, 1);
    var days = [];
    while (date.getMonth() === month) {
        days.push(new Date(date));
        date.setDate(date.getDate() + 1);
    }
    return days;
};


function getDays(date){

    var result = [];

    for(var i = 0; i < 12; i++){
        var r = date.getDaysInMonth(i);

        $.each(r, function(k, v){
            var formatted = v.getDate() + 
               '/' + (v.getMonth() +1) + '/' + v.getFullYear();
            result.push(formatted);
        });
    }

    return result;
}

console.log(getDays(new Date()));

结果:

["1/1/2013", "2/1/2013", "3/1/2013", "4/1/2013"..."]

http://jsfiddle.net/nkMLM/3/

于 2013-10-18T07:35:57.380 回答