Home > Back-end >  moment.js startOf working fine but endOf giving invalid value
moment.js startOf working fine but endOf giving invalid value

Time:08-26

Hi i was just trying to get the start and end date of a month specified to do so i used the moment like below

  //function to get the ranges of month specified
  function Calculate() {
  // get entered month
  const month = document.getElementById('month').value;
  console.log('You entered', month);
  
  //get today date
  //e.g. 25-08-2022
  const today = moment().clone();

  //get delta between required month and current month
  // e.g. 2
  const factor = month - (today.month()   1);

  const startOfMonth = today.add(factor, 'M').clone().startOf('M').format('DD-MM-YYYY');
  const endOfMonth = today.add(factor, 'M').clone().endOf('M').format('DD-MM-YYYY');

  console.log('Ranges', startOfMonth, endOfMonth);
  };
  
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<label>Enter a month to get start & end dates</label><br />
<input type="number" id="month"><br /><br />
<input type="button" value="Calculate" onClick="Calculate()">

The expected output should be like following

Ranges 01-10-2022 31-10-2022

But i am getting the output some thing like below

Ranges 01-10-2022 31-12-2022

the start of the month is right as expected but end of the month is not calculating right.

CodePudding user response:

You're cloning in the wrong place:

today.add(factor, 'M').clone()

This adds factor to today, then clones the result. But today already got changed.

Instead, clone before adding:

today.clone().add(factor, 'M')
  • Related