Search code examples
javascriptreact-nativemomentjsdate-formatting

How to get the start date and end date of a month by passing Month and Year in Moment.js


I am using Moment.js for calendar conversion. Is it possible to get the first and last date of the month by passing month and year.

Month and year format I have is - 10-18 which is in MM-YY format.

I want to get the first and last date of October for instance in 01 Oct 2018. I can format it the date I want in Moment but was not sure how can I get the first and last date of a month by just passing 10-18.

Any help suggestions would be very helpful.

Thanks R


Solution

  • Quite easy, just use startOf and endOf ;)

    Be careful as it mutates the original moment.

    const input = "10-18";
    const output = moment(input, "MM-YY");
    console.log('Start of the month:', output.startOf('month').format('LL'));
    console.log('End of the month:', output.endOf('month').format('LL'));
    <script src="https://momentjs.com/downloads/moment.js"></script>

    Here is the doc: