html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="date.js"></script>
<script>
var d = new getDate();
alert(d.firstWeekDay()); //获取本周第一天日期
alert(d.finaWeekDay()); //获取本周最后一天日期
alert(d.firstDay()); //获取本月第一天
alert(d.endDay()); //获取本月最后一天
alert(d.preDay(6)); //日期往前推6天
alert(d.nextDay(3)); //日期往后推3天
</script>
</body>
</html>
date.js
function getDate(){
this.date = new Date();
this.yy = this.date.getFullYear();
this.mm = this.date.getMonth() + 1;
this.dd = this.date.getDate();
this.ww = ((this.date.getDay() != 0) ? this.date.getDay() : 7);
}
getDate.prototype = {
//获取本周第一天日期
"firstWeekDay": function(){
var nd = this.date.valueOf() - (this.ww - 1) * 24 * 60 * 60 * 1000;
nd = new Date(nd);
return this.dateToString(nd);
},
//获取本周最后一天日期
"finaWeekDay": function(){
var nd = this.date.valueOf() + (7 - this.ww) * 24 * 60 * 60 * 1000;
nd = new Date(nd);
return this.dateToString(nd);
},
// 获取本月第一天
"firstDay": function(){
return this.yy + "-" + this.zero(this.mm) + "-01";
},
// 获取本月最后一天
"endDay": function(){
var nextMonthFirstDay = new Date(this.yy, this.mm, 1);
var oneDay = 1000 * 60 * 60 * 24;
return this.yy + "-" + this.zero(this.mm) +"-"+ this.zero(new Date(nextMonthFirstDay - oneDay).getDate());
},
//日期往前推天数
"preDay": function(day){
var nd = this.date.valueOf() - day * 24 * 60 * 60 * 1000;
nd = new Date(nd);
return this.dateToString(nd);
},
//日期往后推天数
"nextDay": function(day){
var nd = this.date.valueOf() + day * 24 * 60 * 60 * 1000;
nd = new Date(nd);
return this.dateToString(nd);
},
"dateToString": function(date){
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return year + "-" + this.zero(month) + "-" + this.zero(day);
},
"zero": function(num){
return (num<=9)?("0"+num):num;
}
};