MomentJS - 如何获得上个月的最后一天?

时间:2014-11-14 12:44:19

标签: javascript date momentjs

我试图使用以下方式获取上个月的最后一天:

 var dateFrom = moment(dateFrom).subtract(1, 'months').format('YYYY-MM-DD');

其中:

dateFrom = 2014-11-30 

但是在使用

之后
subtract(1, 'months')

它返回日期

DATE_FROM: "2014-10-30"

但是第10个月的最后一天是31。

我该如何解决?

非常感谢您的帮助。

4 个答案:

答案 0 :(得分:89)

只需在您的通话中添加endOf('month')

var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');

http://jsfiddle.net/r42jg/327/

答案 1 :(得分:2)

更简单的解决方案是使用moment.date(0).date()函数占用当月的1到n天,但是,传递零或负数将产生上个月的日期。

例如,如果当前日期是2月3日:

var _date = moment(); // 2018-02-03 (current day)
var _date2 = moment().date(0) // 2018-01-31 (start of current month minus 1 day)
var _date3 = moment().date(4) // 2018-02-04 (4th day of current month)
var _date4 = moment().date(-4) // 2018-01-27 (start of current month minus 5 days)

console.log(_date.format("YYYY-MM-DD"));
console.log(_date2.format("YYYY-MM-DD"));
console.log(_date3.format("YYYY-MM-DD"));
console.log(_date4.format("YYYY-MM-DD"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>

答案 2 :(得分:0)

以当前日期为基础的上个月的第一个日期和上个月的最后一个日期。日期的格式取决于。 (DD-MM-YYYY)

console.log("last month first date");
   const lastmonthlastdate=moment().subtract(1, 'months').startOf('month').format('DD-MM-YYYY')
console.log(lastmonthlastdate);

console.log("lastmonth last date");
   const lastmonthfirstdate=moment().subtract(1, 'months').endOf('month').format('DD-MM-YYYY')
console.log(lastmonthfirstdate);

答案 3 :(得分:0)

您可以获取月份的第一天,然后减去1天即可获得上个月的最后一天。

const monthyear = moment().format('YYYY-MM')
const firstDay = moment(monthyear + "-01").format("YYYY-MM-DD");
// Subtract 1 day to get the end of the previous month
const dateTo = moment(firstDay).subtract('1', 'days').format("YYYY-MM-DD");
相关问题