赞
踩
let now = new Date(); let nowTime = now.getTime(); //当前的时间戳 let nowYear = now.getFullYear(); //当前年 let weekDay = now.getDay(); //当前星期 let lastMonth = now.getMonth(); //上一个月 let oneDayTime = 24 * 3600* 1000; //一天的总毫秒数 let start = ""; //开始日期 let end = ""; //结束日期 let myDate = [] //最终需要的日期数组 [开始,结束] // 1. 上周(最近七天) let week = nowTime - oneDayTime * 7; // oneDayTime * 7 代表一周的总毫秒(ms)数 start = now.setTime(week); end = new Date(); myDate = [formatDate(start), formatDate(end)]; //console.log(myDate , "最近七天"); // 2. 上周(自然周:周一到周日) start = nowTime - (weekDay + 6) * oneDayTime; //上周一的时间戳 end = nowTime - (weekDay + 0) * oneDayTime; //上周日的时间戳 myDate = [formatDate(start), formatDate(end)]; //console.log(myDate , "自然周-上周"); // 3. 上月(最近一个月) let mouth = nowTime - oneDayTime * 30; //oneDayTime * 30 代表一个月的总毫秒数 start = now.setTime(mouth); end = new Date(); myDate = [formatDate(start), formatDate(end)]; //console.log(myDate, "最近一个月"); // 4. 上月(自然月: 每月1号到月末) /* *知识补充: new Date()第3个参数默认为1,就是每个月的1号; 当该参数为0 时,就是每个月的最后一天; *如:获取2022年一月份的天数: new Date("2022","01",0).getDate() //通过getDate()方法得到该月的天数,即31 */ start = new Date(nowYear, lastMonth - 1, 1); //上一个月的第一天日期 end = new Date(nowYear, lastMonth, 0); //上一月的最后一天日期 myDate = [formatDate(start), formatDate(end)]; //console.log(myDate, "自然月-上月"); //格式化日期函数(最终格式yyyy-MM-dd) function formatDate(date) { let myDate = new Date(date); let year = myDate.getFullYear(); let month = myDate.getMonth() + 1; let weekday = myDate.getDate(); if (month < 10) { month = "0" + month; } if (weekday < 10) { weekday = "0" + weekday; } return year + "-" + month + "-" + weekday; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。