js计算上月日期范围
时间: 2023-08-22 07:07:48 浏览: 31
您好!要计算上个月的日期范围,可以使用 JavaScript 中的 Date 对象和一些基本的算术运算符。以下是一个可能的解决方案:
```javascript
// 获取当前日期
const today = new Date();
// 获取上个月的年份和月份
const lastMonthYear = today.getMonth() === 0 ? today.getFullYear() - 1 : today.getFullYear();
const lastMonthMonth = today.getMonth() === 0 ? 11 : today.getMonth() - 1;
// 获取上个月的第一天和最后一天
const firstDayOfLastMonth = new Date(lastMonthYear, lastMonthMonth, 1);
const lastDayOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
// 格式化日期范围
const startDate = `${lastMonthYear}-${lastMonthMonth + 1}-01`;
const endDate = `${lastMonthYear}-${lastMonthMonth + 1}-${lastDayOfLastMonth.getDate()}`;
console.log(`上个月的日期范围是从 ${startDate} 到 ${endDate}`);
```
上述代码首先获取当前日期,然后计算出上个月的年份和月份。接下来,我们使用这些值创建一个新的 Date 对象,分别表示上个月的第一天和最后一天。最后,我们将这些日期格式化为字符串,并在控制台中输出结果。
希望这可以帮助到您!