js获取当前周、月、半年、年的时间区间,yyyy-mm-dd格式
时间: 2023-12-12 19:04:40 浏览: 103
jquery 将当前时间转换成yyyymmdd格式的实现方法
5星 · 资源好评率100%
获取当前周的时间区间:
```javascript
let now = new Date();
let dayOfWeek = now.getDay() || 7;
let thisWeekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1 - dayOfWeek);
let thisWeekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7 - dayOfWeek);
let startDate = thisWeekStart.getFullYear() + '-' + (thisWeekStart.getMonth() + 1) + '-' + thisWeekStart.getDate();
let endDate = thisWeekEnd.getFullYear() + '-' + (thisWeekEnd.getMonth() + 1) + '-' + thisWeekEnd.getDate();
```
获取当前月的时间区间:
```javascript
let now = new Date();
let monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
let monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
let startDate = monthStart.getFullYear() + '-' + (monthStart.getMonth() + 1) + '-' + monthStart.getDate();
let endDate = monthEnd.getFullYear() + '-' + (monthEnd.getMonth() + 1) + '-' + monthEnd.getDate();
```
获取当前半年的时间区间:
```javascript
let now = new Date();
let halfYearStart = new Date(now.getFullYear(), now.getMonth() - 5, 1);
let halfYearEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
let startDate = halfYearStart.getFullYear() + '-' + (halfYearStart.getMonth() + 1) + '-' + halfYearStart.getDate();
let endDate = halfYearEnd.getFullYear() + '-' + (halfYearEnd.getMonth() + 1) + '-' + halfYearEnd.getDate();
```
获取当前年的时间区间:
```javascript
let now = new Date();
let yearStart = new Date(now.getFullYear(), 0, 1);
let yearEnd = new Date(now.getFullYear() + 1, 0, 0);
let startDate = yearStart.getFullYear() + '-' + (yearStart.getMonth() + 1) + '-' + yearStart.getDate();
let endDate = yearEnd.getFullYear() + '-' + (yearEnd.getMonth() + 1) + '-' + yearEnd.getDate();
```
以上代码中,startDate 和 endDate 分别是时间区间的开始和结束日期,格式为 yyyy-mm-dd。
阅读全文