前端实现近一周、近一个月、近一自然周、近一自然月时间获取,默认当前日期为当天
时间: 2025-02-04 10:50:54 浏览: 144
### 实现指定时间段的时间范围
为了实现在前端获取默认今天为结束日的近7天、近30天、最近一个完整的星期和最近一个完整月份的时间段,可以利用 JavaScript 的 `Date` 对象来计算这些日期区间。
#### 近七天时间范围
通过创建一个新的 `Date` 对象并减去相应的毫秒数来获得过去几天的具体日期:
```javascript
function getPastDaysRange(days) {
const today = new Date();
const pastDate = new Date(today);
pastDate.setDate(today.getDate() - days);
return {
start: formatDate(pastDate),
end: formatDate(today)
};
}
function formatDate(date) {
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth() + 1).toString().padStart(2, '0'); // Months are zero-based
let year = date.getFullYear();
return `${year}-${month}-${day}`;
}
```
对于近七天的情况,则调用此函数传入参数7即可得到所需的结果[^1]。
#### 近三十天时间范围
同样的逻辑适用于近三十天的情形,只需调整传递给上述辅助函数的参数值为30即可完成相应功能。
#### 最近的一个完整星期
要取得最近的一整个星期内的所有日子,可以从当前日期出发向前追溯到上一个星期的第一天(即上周日),再往前推算至该周的第一个工作日(周一)。这里假设每周从周一开始计算:
```javascript
function getLastFullWeekRange() {
const today = new Date();
const currentDayOfWeek = today.getDay(); // Sunday is 0, Monday is 1...
const lastSunday = new Date(today);
lastSunday.setDate(today.getDate() - ((currentDayOfWeek === 0 ? 7 : currentDayOfWeek)));
const previousMonday = new Date(lastSunday);
previousMonday.setDate(lastSunday.getDate() - 6); // Go back to the beginning of that week.
return {
start: formatDate(previousMonday),
end: formatDate(lastSunday)
};
}
```
这段代码会返回最近一次完整的那一整周内的起始与终止日期字符串表示形式。
#### 最近的一个完整月份
最后,针对最靠近现在的那个月份内所有有效日期的选择,可以通过设置月初和月末两个极端情况下的日期来进行处理:
```javascript
function getLastFullMonthRange() {
const now = new Date();
const thisYear = now.getFullYear();
const thisMonth = now.getMonth();
const firstDayOfMonth = new Date(thisYear, thisMonth, 1);
const lastDayOfPrevMonth = new Date(firstDayOfMonth);
lastDayOfPrevMonth.setMonth(now.getMonth(), 0); // Set to the last day of the previous month
return {
start: formatDate(new Date(thisYear, thisMonth - 1, 1)),
end: formatDate(lastDayOfPrevMonth)
};
}
```
以上就是基于纯JavaScript实现的不同类型固定周期内日期选取的方法介绍。如果项目中已经集成了某些UI库比如Layui或其他第三方组件,也可以考虑查阅其官方文档寻找是否有内置的支持选项或是插件可以直接满足需求而不必手动编写额外的功能模块。
阅读全文
相关推荐
















