Javascript MomentJS - 如何从日期获取上个月的最后一天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26930338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MomentJS - How to get last day of previous month from date?
提问by redrom
I'm trying to get last day of the previous month using:
我正在尝试使用以下方法获取上个月的最后一天:
var dateFrom = moment(dateFrom).subtract(1, 'months').format('YYYY-MM-DD');
Where:
在哪里:
dateFrom = 2014-11-30
But after using
但是使用后
subtract(1, 'months')
it returns date
它返回日期
DATE_FROM: "2014-10-30"
But last day of the 10'th month is 31.
但是第 10 个月的最后一天是 31。
How can I solve i please?
请问我该如何解决?
Many thanks for any help.
非常感谢您的帮助。
回答by MorKadosh
Simply add a endOf('month')to your calls:
只需endOf('month')在您的通话中添加一个:
var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');
var dateFrom = moment(dateFrom).subtract(1,'months').endOf('month').format('YYYY-MM-DD');
回答by mhodges
An even easier solution would be to use moment.date(0). the .date()function takes the 1 to n day of the current month, however, passing a zero or negative number will yield a dates in the previous month.
一个更简单的解决方案是使用moment.date(0). 该.date()函数取当月的第 1 到 n 天,但是,传递零或负数将产生上个月的日期。
For example if current date is February 3rd:
例如,如果当前日期是 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>
回答by Jojo Joseph
Last month's First date and last month's last date from the current date basis. The Format of the date changes depending upon. (DD-MM-YYYY)
从当前日期开始的上个月的第一个日期和上个月的最后一个日期。日期的格式因人而异。(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);

