查询当前日N天前的日期
/*** 查询当前日N天前的日期* @param {-6} num 为负则为前几天,为正则为后几天* @param {'-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 {-08-19} adate * @param {-08-13} bdate */dateDiff(aDate, bDate) {// '-08-29'转'/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 {'2001'} 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月前或后的当天日期
如-03-31,num为-1,为1月前日期-02-29
如-03-31,num为1,为1月后日期-04-30
/*** 计算N月后的日期* @param {3} num 可为正负* @param {'-08-01'} date */getMonth(num,date){if(date.length>8){date = date.split('-').join('')}var _this = this;var year = date.substring(0,4); // var month = date.substring(4,6); // 08var day = date.substring(6,8); // 01var dayInt = (day.charAt(0) == '0') ? parseInt(day.substring(1)) : parseInt(day); // 1var monthInt = (month.charAt(0) == '0') ? parseInt(month.substring(1)) : parseInt(month); // 8var yearInt = parseInt(year); // var newYear = yearInt; // var newDate = '';var newMonth = monthInt; // 8var newDay = dayInt; // 1 var months = monthInt + num; // 8 + numvar dateVar = date; // -08-01var 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'); // 2001monthDays = 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获取当前日前几天前的日期 两个日期相差天数 当月的天数 几月前的日期》对你有帮助,请点赞、收藏,并留下你的观点哦!