Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

How can I solve i please?

Many thanks for any help.

like image 467
redrom Avatar asked Nov 14 '14 12:11

redrom


People also ask

Why you should not use Momentjs?

However, Moment. js has too many drawbacks compared to modern date and time libraries. Its API is not immutable, it is large and it doesn't support tree shaking. Even the Moment team discourages to use their library in new projects.

How do I compare two dates in Momentjs?

We can use the isAfter method to check if one date is after another. Then we call isAfter on it with another date string and the unit to compare. There's also the isSameOrAfter method that takes the same arguments and lets us compare if one date is the same or after a given unit.

Should you still use Momentjs?

Moment. js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size. Problems with Moment.


2 Answers

Simply add a endOf('month') to your calls:

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

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

like image 139
MorKadosh Avatar answered Sep 24 '22 08:09

MorKadosh


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.

For example if current date is February 3rd:

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>
like image 40
mhodges Avatar answered Sep 23 '22 08:09

mhodges