js获取上个月第一天和最后一天

可以使用JavaScript的Date对象来获取上一个月的第一天和最后一天。

首先,创建一个Date对象,表示当前日期。然后,使用setDate()方法将日期设置为1号,以便我们可以得到上一个月的最后一天:

var today = new Date(); today.setDate(1);

接下来,使用setMonth()方法,将日期的月份设置为上一个月:

today.setMonth(today.getMonth() - 1);

此时,当前日期就是上一个月的第一天。

要获取上一个月的最后一天,可以将月份加1,再将日期设置为0,这样可以回到上一个月的最后一天:

today.setMonth(today.getMonth() + 1); today.setDate(0);

现在,我们可以使用getDate()方法获取上一个月的最后一天,也可以使用toLocaleDateString()方法将日期格式化为更容易阅读的格式:

var lastDayOfLastMonth = today.getDate(); console.log("Last day of last month: " + today.toLocaleDateString());

  •