简体   繁体   English

Momentjs 如何获得下个月的最后日期

[英]Momentjs how to get next month last date

i am trying to get the last date of the next month, for some reason momentjs returns the wrong date我正在尝试获取下个月的最后一天,由于某种原因,momentjs 返回了错误的日期

For Example :例如 :

console.log(moment('02/28/2018', "MM/DD/YYYY").add(i, 'M'));

returns :返回:

moment("2018-03-28T00:00:00.000")

where the right date should be :正确的日期应该在哪里:

moment("2018-03-31T00:00:00.000")

Using .add() you are just adding a month to your actual date but you want also go to last day of this month, and for this you can use .endOf() :使用.add()您只是将一个月添加到您的实际日期,但您还想转到本月的最后一天,为此您可以使用.endOf()

moment('02/28/2018', "MM/DD/YYYY").add(1, 'M').endOf("month")
// 2018-03-31T23:59:59.999Z

You are adding 1 month to 2/28, so you get 3/28.您将 1 个月添加到 2/28,因此您得到 3/28。 It only increases the month part.它只会增加月份部分。

To get the last day of the month, you can use:要获取该月的最后一天,您可以使用:

 // Should be 12/31/2018 23:59:59 console.log(moment("2018-12-01").endOf("month").toString()); // Should be last day, hour, minute, and second of the current month console.log(moment().endOf("month").toString());
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM