这是一个函数,它返回从给定日期之前的第一个星期日到下一个星期日的 Date 实例数组:
function getWeek(fromDate){
var sunday = new Date(fromDate.setDate(fromDate.getDate()-fromDate.getDay()))
,result = [new Date(sunday)];
while (sunday.setDate(sunday.getDate()+1) && sunday.getDay()!==0) {
result.push(new Date(sunday));
}
return result;
}
// usage
var week = getWeek(new Date('2012/10/10'));
console.log(week[0]); //=> Sun Oct 07 2012 00:00:00
console.log(week[6]); //=> Sat Oct 13 2012 00:00:00
只是为了好玩,一个较短的版本(oneliner)使用Array.map
, 作为Date.prototype
Date.prototype.getWeek = function(){
return [new Date(this.setDate(this.getDate()-this.getDay()))]
.concat(
String(Array(6)).split(',')
.map ( function(){
return new Date(this.setDate(this.getDate()+1));
}, this )
);
}
// usage
new Date('2012/10/10').getWeek(); //=> [07/10/2012, ... ,13/10/2012]