js获取上个月的时间
时间: 2023-06-28 22:16:00 浏览: 52
除了上一个回答中提到的获取上个月的年份和月份之外,我们还可以通过 JavaScript 的 Date 对象来获取上个月的具体日期。
具体实现方法如下:
```javascript
// 获取当前日期
var currentDate = new Date();
// 获取上个月的年份和月份
var lastMonthYear = currentDate.getFullYear();
var lastMonthMonth = currentDate.getMonth() - 1;
if (lastMonthMonth < 0) {
lastMonthMonth = 11;
lastMonthYear--;
}
// 创建上个月的日期对象
var lastMonthDate = new Date(lastMonthYear, lastMonthMonth, 1);
// 获取上个月的最后一天日期对象
var lastDayOfLastMonthDate = new Date(lastMonthYear, lastMonthMonth + 1, 0);
// 输出上个月的时间范围
var lastMonthStartDate = lastMonthDate.getFullYear() + "-" + (lastMonthDate.getMonth() + 1) + "-01";
var lastMonthEndDate = lastDayOfLastMonthDate.getFullYear() + "-" + (lastDayOfLastMonthDate.getMonth() + 1) + "-" + lastDayOfLastMonthDate.getDate();
console.log(lastMonthStartDate + " 至 " + lastMonthEndDate);
```
上面的代码中,我们首先创建了一个 Date 对象来表示当前日期。然后,我们通过 `getMonth()` 方法获取当前月份,再减去 1,就可以得到上个月的月份。需要注意的是,如果当前月份是 1 月,那么上个月应该是 12 月,所以需要将月份设置为 11,同时年份也需要减 1。
接着,我们使用 `new Date(year, month, day)` 的方式来创建上个月的日期对象和上个月的最后一天日期对象。注意,在创建上个月的日期对象时,我们将日期设置为 1,这样可以得到上个月的第一天日期对象。
最后,我们将上个月的起始日期和结束日期输出到控制台中。需要注意的是,由于月份从 0 开始,所以在输出月份时需要将其加 1。