js日期处理多少/月/天以前
var date = new Date(); var year = date.getFullYear(); var month = (date.getMonth() + 1) > 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1); var day = date.getDate() > 10 ? date.getDate() : '0' + date.getDate(); var nowdatestr = year + "-" + month + "-" + day; var darr1=""; //近3天 function getDay(day) { var today = new Date(); var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day; today.setTime(targetday_milliseconds); //注意,这行是关键代码 var tYear = today.getFullYear(); var tMonth = today.getMonth(); var tDate = today.getDate(); tMonth = doHandleMonth(tMonth + 1); tDate = doHandleMonth(tDate); return tYear + "-" + tMonth + "-" + tDate; } function doHandleMonth(month) { var m = month; if (month.toString().length == 1) { m = "0" + month; } return m; } //近7天 $("#sevenday").click(function () { var oneweekdate = new Date(date - 6 * 24 * 3600 * 1000); var year1 = oneweekdate.getFullYear(); var month1 = oneweekdate.getMonth() + 1 > 10 ? oneweekdate.getMonth() + 1 : '0' + oneweekdate.getMonth() + 1; var day1 = oneweekdate.getDate() > 10 ? oneweekdate.getDate() : '0' + oneweekdate.getDate(); $("#begin_time").val(year1 + "-" + month1 + "-" + day1); }); //近1个月 $("#onemonth").click(function () { $("#begin_time").val(getPreMonthDay(nowdatestr, 1)); }); //近3个月 $("#threemonth").click(function () { $("#begin_time").val(getPreMonthDay(nowdatestr, 3)); }); //获取当前日期前N个月的日期 function getPreMonthDay(date, monthNum) { var dateArr = date.split('-'); console.log(dateArr) var year = dateArr[0]; //获取当前日期的年份 var month = dateArr[1]; //获取当前日期的月份 var day = dateArr[2]; //获取当前日期的日 var days = new Date(year, month, 0); days = days.getDate(); //获取当前日期中月的天数 var year2 = year; var month2 = parseInt(month) - monthNum; if (month2 <= 0) { year2 = parseInt(year2) - parseInt(month2 / 12 == 0 ? 1 : parseInt(month2) / 12); month2 = 12 - (Math.abs(month2) % 12); } var day2 = day; var days2 = new Date(year2, month2, 0); days2 = days2.getDate(); if (day2 > days2) { day2 = days2; } if (month2 < 10) { month2 = '0' + month2; } var t2 = year2 + '-' + month2 + '-' + day2; return t2; } //重写toLocaleString把时间戳转换为想要的格式 Date.prototype.toLocaleString = function () { return this.getFullYear().toString() + "-" + (this.getMonth() + 1).toString() + "-" + this.getDate().toString() + " " + this.getHours().toString() + ":" + this.getMinutes().toString() + ":" + this.getSeconds().toString(); };
一点点学习,一丝丝进步。不懈怠,才不会被时代淘汰