简体   繁体   English

MomentJS - 如何从日期获取上个月的最后一天?

[英]MomentJS - How to get last day of previous month from date?

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.非常感谢您的帮助。

Simply add a endOf('month') to your calls:只需在您的电话中添加一个endOf('month')

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

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

An even easier solution would be to use moment.date(0) .一个更简单的解决方案是使用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. .date()函数取.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>

moment().subtract(1, 'months').endOf('month').format('YYYY-MM-DD') moment().subtract(1, '月').endOf('月').format('YYYY-MM-DD')

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);

You can get the first day of the month then subtract 1 day to get the last day of the previous month.您可以获取该月的第一天,然后减去 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");

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

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