获取当年的所有自然周+获取当前是第几自然周+JS获取指定日期的前一天,后一天
作者:互联网
直接上代码:
获取当年的所有自然周 getWeeks() { var year = new Date().getFullYear(); // 当年的年份 var data = [] var d = new Date(year, 0, 1); while (d.getDay() != 1) { d.setDate(d.getDate() - 1); } var to = new Date(year + 1, 0, 1); var i = 1; for (var from = d; from < to;) { // 这的代码可以优化一下 var str = ''; str = str + (i < 10 ? '0' + i : i) + "(周)" + year + "-" + ((from.getMonth() + 1) <= 9 ? ('0' + (from.getMonth() + 1)) : (from.getMonth() + 1)) + "-" + (from.getDate() <= 9 ? ('0' + from.getDate()) : from.getDate()) + " 至 "; from.setDate(from.getDate() + 6); if (from < to) { str = str + year + "-" + ((from.getMonth() + 1) <= 9 ? ('0' + (from.getMonth() + 1)) : (from.getMonth() + 1)) + "-" + (from.getDate() <= 9 ? ('0' + from.getDate()) : from.getDate()); from.setDate(from.getDate() + 1); } else { to.setDate(to.getDate() - 1); str = str + year + "-" + ((to.getMonth() + 1) <= 9 ? ('0' + (to.getMonth() + 1)) : (to.getMonth() + 1)) + "-" + (to.getDate() <= 9 ? ('0' + to.getDate()) : to.getDate()); } var obj = { sun: i, week: year + "-" + str.split("(周)")[0], weekName: year + "-" + str.split("(周)")[0] + "(周)", startDate: str.split("(周)")[1].split(" 至 ")[0], entData: str.split("(周)")[1].split(" 至 ")[1] } data.push(obj) i++; } return data; }, 获取当前是第几自然周 getWeek() { var today = new Date(); // 当天日期 var firstDay = new Date(today.getFullYear(), 0, 1); var dayOfWeek = firstDay.getDay(); var spendDay = 1; if (dayOfWeek != 0) { spendDay = 7 - dayOfWeek + 1; } firstDay = new Date(today.getFullYear(), 0, 1 + spendDay); var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000); var result = Math.ceil(d / 7); return result + 1; // 直接返回第几自然周,如:34 }, JS获取指定日期的前一天,后一天 // date 代表指定的日期,格式:2018-09-27 // day 传-1表始前一天,传1表始后一天 // JS获取指定日期的前一天,后一天 getNextDate(date, day) { var dd = new Date(date); dd.setDate(dd.getDate() + day); var y = dd.getFullYear(); var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1; var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate(); return y + "-" + m + "-" + d; //(可以自定义返回值) },标签:第几,dd,Date,获取,var,new,JS,getDate 来源: https://www.cnblogs.com/wu2020/p/12956946.html