js 日期天数相加减,格式化yyyy-MM-dd

参数格式:

date :2016-03-02

days:-3(2)当为负数的时候日期往前推,为正数,日期往后推 

function addDate(date, days) {
var d = new Date(date);
d.setDate(d.getDate() + days);
var m = d.getMonth() + 1;
var da = d.getDate();
if (m<10) {
m = '0' + m;
}
if (da<10) {
da = '0' + da;
}
return d.getFullYear() + '-' + m + '-' +da;
}

//方法调用

$(function myfunction() {
var td = "2016-03-02"
var hg = addDate(td, -3);

var now = new Date();
var nowStr = now.format("yyyy-MM-dd");

}

//日期格式yyyy-MM-dd hh:mm:ss 可以自己定义不要时分秒
Date.prototype.format = function (format) {
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //day
"h+": this.getHours(), //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() //millisecond
}

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] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}

原文地址:https://www.cnblogs.com/luoqin520/p/5457902.html