js 日报 周报 月报 时间扩展 js

时间:2023-03-09 03:08:36
js 日报 周报 月报  时间扩展 js
当初做统计业务需要处理时间 周报:本周 上周 下周 近一周    月报上月 本月  等 需要使用时间处理 所以扩展了这些方法 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body> </body>
</html>
<script type="text/javascript">
var _DateTostring = Date.prototype.toString;
Date.prototype.add = function (type, value) {
if (!type || value==undefined||value==null || isNaN(value)) {
throw "增加的类型不存在或者值不是一个数字"
}
switch (type) {
case "d":
case "D":
this.setDate(this.getDate() + value);
break
case "M":
case "m":
this.setMonth(this.getMonth() + value);
break;
case "Y":
case "y":
this.setFullYear(this.getFullYear() + value);
break;
case "day":
case "DAY":
//本周的第几天
var day =this.getDay()==0?7:this.getDay(); var i = Math.abs(value);
if (value == 0) { this.addDate(-(day-1));//本周
return;
}
value < 0 ? this.addDate(-(day + 7 * i - 1)) : i > 1 ? this.addDate(7 - day + ((i - 1) * 7)+1) : this.addDate(7 - day+1); break;
}
var date = this;
return date;
}
Date.prototype.addDate = function (value) {
this.add("d", value);
}
Date.prototype.addMonth = function (value) {
this.add("m", value);
}
Date.prototype.addDay = function (value) {
this.add("day", value);
}
Date.prototype.addYear = function (value) {
this.add("y", value);
}
Date.prototype.toString = function (fmt) {
if (fmt == undefined) {
return _DateTostring.call(this);
}
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
var date = new Date();
//date.addDate(1);//当前时间基础加上12天
//date.addDate(-1);//当前时间基础减去12天
//date.addMonth(-1);//当前时间基础减去1月
//date.addMonth(1);//当前时间基础加上一月
//date.addYear(1);//当前时间基础加上一年
//date.addYear(-1);//当前时间基础减去一年
//date.addDay(-1);//上周
//date.addDay(-2);//前2周
//date.addDay(0);//本周
//console.log(date.toString("yyyy-MM-dd"));//格式化日期
// console.log(date.toString());
// date.addDay(-1);//下周 </script>