查询当前日N天前的日期
/**
* 查询当前日N天前的日期
* @param {-6} num 为负则为前几天,为正则为后几天
* @param {'2020-08-01'} aDate
*/
getDate(num,aDate) {
var d = aDate ? new Date(aDate) : new Date();
var date = d.getDate();
num = num ? num : 0;
d.setDate(date + num);
date = d.getDate();
var year = d.getFullYear();
var month = (d.getMonth() + 1) < 10 ? ('0' + (d.getMonth() + 1)) : (d.getMonth() + 1);
var day = d.getDate() < 10 ? ('0' + d.getDate()) : d.getDate();
return year + '-' + month + '-' + day;
},
计算两个日期相差天数
/**
* 计算2个日期相差的天数
* @param {2020-08-19} adate
* @param {2020-08-13} bdate
*/
dateDiff(aDate, bDate) {
// '2020-08-29'转'2020/08/29'
var s1=aDate.replace(/-/g,"/");
var s2=bDate.replace(/-/g,"/");
var d1 = new Date(s1);
var d2 = new Date(s2);
// 获取相差天数的时间戳
var time = d1.getTime() - d2.getTime();
return parseInt(time / (1000 * 60 * 60 * 24))
}
获取传入日期,当月的天数
/**
* 获取某月份的天数
* @params {'20200801'} date
*/
getMonthDays(date){
var _this = this;
var year = date.substring(0,4);
var month = date.substring(4,6);
var monthInt = (month.charAt(0) == '0')
? parseInt(month.substring(1))
: parseInt(month);
var yearInt = parseInt(year);
// 判断是否闰年
var leapYear = ((yearInt % 4 == 0) || (yearInt & 100 !==0) || (yearInt % 400 ==0))
? true :false;
var monthDay = new Array(12);
monthDay[0] = 31;
monthDay[1] = leapYear ? 29 : 28;
monthDay[2] = 31;
monthDay[3] = 30;
monthDay[4] = 31;
monthDay[5] = 30;
monthDay[6] = 31;
monthDay[7] = 31;
monthDay[8] = 30;
monthDay[9] = 31;
monthDay[10] = 30;
monthDay[11] = 31;
return monthDay[monthInt - 1]
},
计算N月前或后的当天日期
如2020-03-31,num为-1,为1月前日期2020-02-29
如2020-03-31,num为1,为1月后日期2020-04-30
/**
* 计算N月后的日期
* @param {3} num 可为正负
* @param {'2020-08-01'} date
*/
getMonth(num,date){
if(date.length>8){
date = date.split('-').join('')
}
var _this = this;
var year = date.substring(0,4); // 2020
var month = date.substring(4,6); // 08
var day = date.substring(6,8); // 01
var dayInt = (day.charAt(0) == '0')
? parseInt(day.substring(1))
: parseInt(day); // 1
var monthInt = (month.charAt(0) == '0')
? parseInt(month.substring(1))
: parseInt(month); // 8
var yearInt = parseInt(year); // 2020
var newYear = yearInt; // 2020
var newDate = '';
var newMonth = monthInt; // 8
var newDay = dayInt; // 1
var months = monthInt + num; // 8 + num
var dateVar = date; // 2020-08-01
var monthDays = 0;
if (num >= 0) { // 日期往后
while (months > 12) {
months -=12;
newYear++
}
} else {
while (month < 1) {
months +=12;
newYear--
}
}
newMonth = months;
dateVar = (newYear + '') + (newMonth < 10
? ('0' + newMonth)
: ('' + newMonth) + '01'); // 20201001
monthDays = this.getMonthDays(dateVar);
if (dayInt < monthDays) {
newDay = dayInt;
} else {
newDay = monthDays;
}
newDate = (newYear + '') + '-' + (newMonth < 10
? ('0' + newMonth)
: ('' + newMonth))
+ '-' + (newDay < 10 ? ('0' + newDay) : newDay);
return newDate;
},
做个记录,随去随用。
标签:天数,JS,date,日期,num,2020,var,month,monthDay From: https://blog.csdn.net/qq_54548545/article/details/140170068