JS 获取近30天的时间
时间: 2025-09-03 18:14:08 AIGC 浏览: 8
在JavaScript中,有多种方法可以获取近30天的时间,以下为你介绍几种常见的方式:
### 使用纯JavaScript获取近30天日期
```javascript
function getLast30Days() {
const timeArr = [];
const now = new Date();
for (let i = 0; i < 30; i++) {
const newDate = new Date(now);
newDate.setDate(now.getDate() - i);
const year = newDate.getFullYear();
const month = String(newDate.getMonth() + 1).padStart(2, '0');
const day = String(newDate.getDate()).padStart(2, '0');
const dateStr = `${year}-${month}-${day}`;
timeArr.push(dateStr);
}
return timeArr;
}
const last30Days = getLast30Days();
console.log(last30Days);
```
这种方法是通过循环30次,每次将当前日期减去相应的天数来获取过去30天的日期。
### 在Vue中动态获取近30天日期
```javascript
// 假设在Vue组件中
export default {
data() {
return {
dateDate30: 30,
y: '',
m: '',
d: '',
};
},
methods: {
times(n1, n2, n3 = 0) {
let date;
if (n1) {
date = new Date(n1, n2, n3);
} else {
date = new Date();
}
this.y = date.getFullYear();
this.m = date.getMonth();
this.d = date.getDate();
},
timeList() {
this.times();
let y = this.y;
let m = this.m;
let d = this.d;
const dateNum = this.dateDate30;
const dataKey = [];
while (true) {
for (let i = d; i > d - dateNum; i--) {
if (i === 0) break;
const ms = (m + 1).toString().padStart(2, '0');
const is = i.toString().padStart(2, '0');
dataKey[`${ms}${is}`] = `${m + 1}月${i}`;
}
if (dateNum - d >= 0) {
dateNum -= d;
this.times(y, m);
y = this.y;
m = this.m;
d = this.d;
} else {
break;
}
}
console.log(dataKey);
},
},
mounted() {
this.timeList();
},
};
```
该方法在Vue组件中使用,通过循环和日期计算获取近30天的日期信息。
### 封装函数获取近30天日期数组
```javascript
function getNearMonth() {
const timeArr = [];
const time = new Date();
const year = time.getFullYear();
const lastMonth = time.getMonth();
const nowMonth = time.getMonth() + 1;
function getDaysInOneMonth(year, lastMonth) {
lastMonth = parseInt(lastMonth, 10);
const newTime = new Date(year, lastMonth, 0);
return newTime.getDate();
}
const lastDays = getDaysInOneMonth(year, lastMonth);
const nowDays = getDaysInOneMonth(year, nowMonth);
let day = time.getDate() + 1;
for (let i = 0; i < nowDays; i++) {
day = day - 1;
if (day <= 0) {
day = day + lastDays;
}
timeArr.push(day);
}
timeArr.reverse();
timeArr.splice(1, nowDays);
console.log(timeArr);
return timeArr;
}
getNearMonth();
```
这个方法将获取近30天日期数组封装成了一个函数,通过计算上个月和本月的天数来生成日期数组。
阅读全文
相关推荐



















