87,907
社区成员
发帖
与我相关
我的任务
分享
Date.prototype.Format = function (fmt) { //author: meizz
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;
var year=date.getFullYear();
var month=date.getMonth()+1;
month =(month<10 ? "0"+month:month);
var half_month = (year.toString()+month.toString()-7);//6个月前
var month = (year.toString()+month.toString()-1);//上月
var yday=new Date(new Date().getTime()-1*24*60*60*1000).Format("yyyy-MM-dd");//昨天
var tday=new Date(new Date().getTime()).Format("yyyy-MM-dd");//今天
window.console = window.console || {log:function(s){alert(s);}};
Date.prototype.calcAndFormat = function(num,type,format){
var m = this.getMonth();
var d = this.getDate();
if(type == 1){//天
this.setDate(d + num);
}else if(type == 2){//月
this.setMonth(m + num)
}
var o = {
"M+": this.getMonth()+1 , //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('0'+o[k]).slice(-2));
return format;
}
var D = new Date();
var format = D.calcAndFormat(-1,1,'yyyy-MM-dd');
console.log(format);
var d = new Date(); // 获取当前时间
var yesterday = new Date(d.getFullYear(),d.getMonth(),d.getDate()-1); // 日期位减1,表示前一天
var half_years_ago = new Date(d.getFullYear(),d.getMonth()-6,d.getDate()); // 月份位减6,表示六个月前
Date.prototype.addDays = function (d) {
return new Date(this.valueOf() + d * 24 * 60 * 60 * 1000);
}
alert(new Date().addDays(7));
alert(new Date().addDays(-1));
按这个思路你自己扩展一下