相差月数
/**
* 相差月数
* @param s_time 开始时间
* @param e_time 结束时间
* @param type String 月数加减 1:加;2:减
* @param num int 月数
*/
getMonthsApart: function (s_time, e_time, type, num) {
var _this = this,
s = _this.stringToDate(s_time),
e = _this.stringToDate(e_time),
s_year = s.getFullYear(),
s_month = s.getMonth(),
s_day = s.getDate(),
s_hour = s.getHours(),
e_year = e.getFullYear(),
e_month = e.getMonth(),
e_day = e.getDate(),
e_hour = e.getHours(),
sum = (e_year - s_year) * 12 + (e_month - s_month);
if ((e_day - s_day < 0) || ((e_day === s_day) && (e_hour > s_hour))) {
sum -= 1;
}
if (type && typeof (num) === 'number') {
if (type === '1') {
sum += num;
} else {
sum -= num;
}
}
return sum;
},
时间加减
getHandleDate: function (time, obj) {
var date = this.stringToDate(time);
if (!date) {
return;
}
var opt = $.extend({
yearType: '0',
monthType: '0',
dayType: '0',
year: null,
month: null,
day: null
}, obj || {}),
s;
if (opt.year) {
s = date.getFullYear();
if (opt.yearType === '0') {
s += opt.year;
} else {
s -= opt.year;
}
date.setFullYear(s);
}
if (opt.month) {
s = date.getMonth();
if (opt.monthType === '0') {
s += opt.month;
} else {
s -= opt.month;
}
date.setMonth(s);
}
if (opt.day) {
s = date.getDate();
if (opt.dayType === '0') {
s += opt.day;
} else {
s -= opt.day;
}
date.setDate(s);
}
return date;
},
字符转日期
/**
*@param dateStr 日期格式的字符串
*/
stringToDate: function (dateStr) {
if (typeof dateStr === 'undefined') {
return new Date();
}
if (typeof dateStr === 'object') {
return dateStr;
}
var converted = Date.parse(dateStr),
myDate = new Date(converted);
if (isNaN(myDate)) {
dateStr = dateStr.replace(/:/g, '-'); // 支持 2013:10:17
dateStr = dateStr.replace(' ', '-'); // 支持 2013 10 17
dateStr = dateStr.replace('.', '-'); // 支持 2013.10.17
var arys = dateStr.split('-'); // 支持2013-10-17
switch (arys.length) {
case 7: // 2013-10-17-13-56-33-22 格式
myDate = new Date(arys[0], parseInt(arys[1], 10) - 1, arys[2], arys[3], arys[4], arys[5], arys[6]);
break;
case 6: // 2013-10-17-13-56-33 格式
myDate = new Date(arys[0], parseInt(arys[1], 10) - 1, arys[2], arys[3], arys[4], arys[5]);
break;
default: // 2013-10-17 格式
myDate = new Date(arys[1] + '/' + arys[2] + '/' + arys[0]);
break;
}
}
return myDate;
},
比较两日期大小
/**
* 比较两日期大小
* @param time1
* @param time2
* @returns 0:time1小于time2;
* 1:time1大于time2;
* 2:time1等于time2
*/
comPareDate: function (time1, time2) {
var a = this.stringToDate(time1).getTime(),
b = this.stringToDate(time2).getTime(),
c = 0;
if (a > b) {
c = 1;
} else if (a === b) {
c = 2;
}
return c;
},
计算一年前的今天
oneYearPast = (time) => {
//var time=new Date();
var year = time.getFullYear() - 1;
var month = time.getMonth() + 1;
var day = time.getDate();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
if (day > 1) {
// day = day - 1;
} else {
// month = month - 1;
if (month < 10) {
month = "0" + month;
}
if (month == 0) {
month = 12;
}
day = new Date(year, month, 0).getDate();
}
var v2 = year + '-' + month + '-' + day;
return v2;
}