Search code examples
vue.jsquasar

quasar get month in between using date


const dateEnd = date.formatDate(timeStamp, ‘MMM YYYY’)

const dateStart = date.subtractFromDate(dateEnd, { month: 10 })

I have these two dates, I need a list of months between dateStart and dateEnd. May I know how can I get it?


Solution

  • Quasar framework has a number of utils that can help you. In this case, we will import the date utils from quasar like so.

    import { date } from 'quasar';
    

    The date util has functions for formatting, adding, subtracting dates, etc. I understand you have an end-date that you want to find a list of 11 months (end-date inclusive) from the start-date to the end-date.

    let dateEnd = date.formatDate('2021/12/25', 'YYYY MMM D'); // e.g '2021/12/25'
    let dateStart = date.subtractFromDate(dateEnd, { month: 10 });
    

    You can achieve this by using a while loop, a counter at 0, and addToDate method of the date util.

    let counter = 0;
    let newDate = dateStart;
    let monthsList = [];
    while(counter <= 10){
      monthsList.push(date.formatDate(newDate, 'MMM'));
        newDate = date.addToDate(newDate, { month: 1 });
         counter++;
    }
    // output [ "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
    

    Alternatively, you can use the array unshift method, a countdown from 10 and subtractFromDate method.

    let counter = 10;
    let newDate = dateEnd;
    let monthsList = [];
    while(counter >= 0){
      monthsList.unshift(date.formatDate(newDate, 'MMM'));
      newDate = date.subtractFromDate(newDate, { month: 1 });
      counter--;
    }
    

    You can read more about the date util in quasar here: https://quasar.dev/quasar-utils/date-utils