admin管理员组文章数量:1355694
i am trying to get the last date of the next month, for some reason momentjs returns the wrong date
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")
i am trying to get the last date of the next month, for some reason momentjs returns the wrong date
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")
Share
Improve this question
asked Mar 6, 2018 at 2:51
publicArt33publicArt33
3159 silver badges16 bronze badges
4
- 2 a) get todays date. b) set date to 1. c) add 2 months ... d) subtract 1 day – Jaromanda X Commented Mar 6, 2018 at 2:52
- 1 adding 1 month to the 'n'th day of 'm' will result in the 'n'th day of 'm+1' - so, how is that wrong? – Jaromanda X Commented Mar 6, 2018 at 2:53
-
@JaromandaX—you don't need to set the date first, month and date can be in one go, e.g. in POJS you can do:
var d = new Date(2017,11,31); d.setMonth(d.getMonth() + 2, 0);
returns 31 Jan. Adding 2 months doesn't roll over an extra month by adding the months first then the date, both month and date are set at the same time. ;-) – RobG Commented Mar 6, 2018 at 3:34 - I never knew that about setMonth! learn something every day – Jaromanda X Commented Mar 6, 2018 at 4:52
3 Answers
Reset to default 7Using .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()
:
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. 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./ajax/libs/moment.js/2.21.0/moment.min.js"></script>
Another variation of guijob's answer, if you want to get based on current day you can use
moment().add(1, "month").endOf("month")
本文标签: javascriptMomentjs how to get next month last dateStack Overflow
版权声明:本文标题:javascript - Momentjs how to get next month last date - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743958615a2568597.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论