前言
本片文章主要记录一下遇到的问题,js计算当前一周的日期。感兴趣的小伙伴可以学习一下。
提示:以下是本篇文章正文内容,下面案例可供参考
一、Date日期对象
Date()日期对象 是一个构造函数,必须使用new 来调用创建我们的日期对象使用Date日期对象的时候,如果里面没有放置参数,那么返回的就是系统的当前时间
常用方法 | 说明 |
---|---|
getFullYear() | 返回当前日期的年份 |
getMonth() | 返回当前日期的月份 但是返回值是在0-11,我们需要在获取到的月份上 进行+1的操作 |
getDate() | 返回的是当前日期的天数,也就是今天是几号 |
getDay() | 返回的是今天是星期几 周一返回的是1,周六返回的是6 但是周日返回的是0 |
getHours() | 返回的是当前的小时 |
getMinutes() | 返回的是当前的分钟数 |
getSeconds() | 返回的是当前的秒数 |
getTime() | 获取毫秒数 |
setFullYear() | 为指定日期设置年 |
setDate() | 设置指定的日期 |
setHours() | 设置指定日期设置小时 |
setMinutes() | 设置指定日期的分钟数 |
setSeconds() | 设置指定日期的秒数 |
二 获取当前一周的日期
要获取当前一周的日期,我们可以先计算周一的日期,然后通过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)