Search code examples
javascriptnode.jsmoment-timezone

Can I get the monthly cycle using moment.js for every months?


i want to run a query from last month's 15 January and current month's 14th February. and i want to run the logic in such a way that this follows for next months also like from 15th February to 14th March. I certainly don't know how to proceed with this problem using moment.js

like I want to get the last months' 15th date and current months 14th for each month. think like a cycle where the cycle starts from 15th of the previous months and ends with this months 14th


Solution

  • Given a moment instance called date the following method calculates the 15th of the previous month to the 14th of the current month (where "current" date is date parameter):

    function getRange(date){
      var start = date.clone().startOf("month").add(-1,'months').add(14,'days');
      var end = date.clone().startOf("month").add(13,"days");
      return [start,end];
    }
    

    A live example with 2 test cases can be seen in the demo below.

    var testArr = [
       moment(),
       moment({y:2019,M:11,d:31}) // 31 december 2019. (Yes months are zero based!)
    ];
    
    for(var i=0;i<testArr.length;i++){
        var [start,end] = getRange(testArr[i]);
        console.log(start,' --> ',end);
    }
    
    
    function getRange(date){
      var start = date.clone().startOf("month").add(-1,'months').add(14,'days');
      var end = date.clone().startOf("month").add(13,"days");
      return [start,end];
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>