Moment: Get last day of the month?

Created on 30 Mar 2012  ·  10Comments  ·  Source: moment/moment

Will be great to be able to get/set moment instance to last day of the month - similar to eod.

New Feature

Most helpful comment

moment().endOf('month');

works since 1.7

All 10 comments

I guess for now this works:
moment().add('months', 1).date(1).subtract('days', 1)

Also, the setters overflow if they are out of range.

moment().date(0); // the last day of last month
moment().date(-1); // the second to last day of last month
moment().hours(25); // 1 am the next day

So you could do something like this...

moment().add('months', 1).date(0);
moment().endOf('month');

works since 1.7

moment().endOf('month');

or

moment(year-month-day).endOf('month');

@lance-ding Thanks! That's was definitely helpful.

I still think it would be nice to have a .format() option for the number of days in the current month.

Related: you can also use moment().daysInMonth() to get an integer representing the last day in the month.

Related:

Deprecation warning:
moment().add(period, number) is deprecated. Please use moment().add(number, period).

So a little change to the code would be: moment().add(1, 'months').date(1).subtract('days', 1)

@gideonapollob , yep. You would need to reverse in your .subtract() as well.

But .endOf() is almost for sure the best choice for what you're doing.

You may get last day of month. like this.

moment(2017-10).endOf('month').format('DD')

which shows last month last date

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ninigix picture ninigix  ·  3Comments

BCup picture BCup  ·  3Comments

IbraheemAlSaady picture IbraheemAlSaady  ·  3Comments

Delgan picture Delgan  ·  3Comments

slavafomin picture slavafomin  ·  3Comments