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.
非常感谢任何帮助。
2 个解决方案
#1
78
Simply add a endOf('month')
to your calls:
只需在您的通话中添加endOf('月')即可:
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');
#2
1
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>
#1
78
Simply add a endOf('month')
to your calls:
只需在您的通话中添加endOf('月')即可:
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');
#2
1
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>