获取昨天,上个月,过去7天,过去14天,过去N天都可以等
2023-03-03 11:22 WEB前端小菜鸟 阅读(25) 评论(0) 编辑 收藏 举报
过去N天,爽得一批
//过去7天,过去14天,过去30天 想要过去几天参数就传几就行了
getBeforeDate(n) { var n = n; var d = new Date(); var year = d.getFullYear(); var mon = d.getMonth() + 1; var day = d.getDate(); if (day <= n) { if (mon > 1) { mon = mon - 1; } else { year = year - 1; mon = 12; } } d.setDate(d.getDate() - n); year = d.getFullYear(); mon = d.getMonth() + 1; day = d.getDate(); let s = year + "-" + (mon < 10 ? "0" + mon : mon) + "-" + (day < 10 ? "0" + day : day); return s; },
//
console.log(this.getBeforeDate(1),'88888') // 2023-03-02
console.log(this.getBeforeDate(5),'88888') // 2023-02-26
默认半年前
// 获取近半年时间 const getNowdate=(time = 6)=> { let date = new Date() let year = date.getFullYear() let month = date.getMonth() let olddate = new Date(year, month - time).getTime() let date2 = new Date(olddate); let year2 = date2.getFullYear(); let month2 = date2.getMonth() + 1; month2 = (month2<10)? '0'+ month2 : month2; let currentDate = year2 + "-" + month2 console.log(currentDate,'半年前的月份') } const formatDateMy=() =>{ let date = new Date(); let year = date.getFullYear(); let month = date.getMonth() + 1; month = (month<10)? '0'+ month : month; let currentDate = year + "-" + month console.log(currentDate,'现在的月份') return currentDate; }