前言
本片文章主要记录一下遇到的问题,js计算当前一周的日期。感兴趣的小伙伴可以学习一下。
提示:以下是本篇文章正文内容,下面案例可供参考
一、Date日期对象
Date()日期对象 是一个构造函数,必须使用new 来调用创建我们的日期对象使用Date日期对象的时候,如果里面没有放置参数,那么返回的就是系统的当前时间
var date = new Date();// 调用Date()这个日期函数
console.log(date.getFullYear()); //返回当前日期的年份
console.log(date.getMonth()+1); //返回当前日期的月份,但是返回值是在0-11,我们需要在获取到的月份上 进行+1的操作,然后输出结果。
console.log(date.getDate()); //返回的是当前日期的天数,也就是今天是几号
console.log(date.getDay()); //返回的是今天是星期几 周一返回的是1,周六返回的是6 但是周日返回的是0
console.log(date.getHours());//返回的是当前的小时
console.log(date.getMinutes());//返回的是当前的分钟数
console.log(date.getSeconds());//返回的是当前的秒针数
二、分析
要获取当前一周的日期,我们可以先计算周一的日期,然后通过for循环循环6次,就可以得到一周的时间。
三 代码
getWeeks() {
let weeks = [];
let currentDate = new Date();
let day = currentDate.getDay();
if (day === '0') {
currentDate.setDate(currentDate.getDate() - 6);
} else {
currentDate.setDate(currentDate.getDate() - day + 1);
}
// 得到周一的日期
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1 < 10 ? '0' + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1;
let date = currentDate.getDate() < 10 ? '0' + currentDate.getDate() : currentDate.getDate();
weeks.push(year + '-' + month + '-' + date);
for (var i = 0; i < 6; i++) {
currentDate.setDate(currentDate.getDate() + 1);
year = currentDate.getFullYear();
month = currentDate.getMonth() + 1 < 10 ? '0' + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1;
date = currentDate.getDate() < 10 ? '0' + currentDate.getDate() : currentDate.getDate();
weeks.push(year + '-' + month + '-' + date);
}
console.log(weeks);
},
四 注意点
1.date.setDate(dayValue)
date.setDate(dayValue):设置指定日期对象 date 的月份中的某一天。如果 dayValue 大于该月的实际天数,日期会相应地进行调整(例如,将 2 月 30 日自动调整为 3 月 1 日)
let date = new Date("2024-08-01");
date.setDate(15);
console.log(date); // 输出:Wed Aug 15 2024 00:00:00 GMT+0800 (中国标准时间)
在上面的示例中,date.setDate(15) 将日期对象 date 的天数设置为 15,这意味着日期变为了 2024 年 8 月 15 日。
2.date.setDate(-2)
1.如果你调用 date.setDate(-2),它会将日期设置为上个月的倒数第三天。
2.例如,假设当前日期是 2024 年 8 月 1 日,那么 date.setDate(-2) 将会将日期设置为 2024 年 7 月 29 日。
let date = new Date("2024-08-01");
date.setDate(-2);
console.log(date);