JavaScript获取前后几天的日期 题记:开发中遇到的一些小问题,在这里整理整理,做一下记录 获取当前日期、几天前(-)或几天后(+) function getDateString(index) { var date = new Date();// 获取date对象 var newDate = new Date(); var minuts = date.getTime() + 1000 * 60 * 60 * 24 * parseInt(index); newDate.setTime(minuts);// 新日期 var year = newDate.getFullYear();// 年(2018) var month = (newDate.getMonth() + 1) >= 10 ? newDate.getMonth() + 1 : '0' + (newDate.getMonth() + 1);// 月 var day = newDate.getDate() >= 10 ? newDate.getDate() : '0' + newDate.getDate();// 日 return year + '-' + month + '-' + day;// 返回yyyy-MM-dd格式的日期,例:2018-04-20 } // 测试 getDateString(0);// 获取当天的日期,例:2018-04-20 console.log('今天的日期是:' + getDateString(0)); getDateString(7);// 获取7天后的日期,例:2018-04-27 console.log('7天后的日期是:' + getDateString(7)); getDateString(-7);// 获取7天前的日期,例:2018-04-13 console.log('7天前的日期是:' + getDateString(-7)); // 这里多说两句:2018-04-13到2018-04-20,算上20号,应该是有8天的。