简体   繁体   中英

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?

You can use the library such as moment.js( https://www.npmjs.com/package/vue-moment ). You can use CDN as well for the same. It makes it easy to manipulate dates.

You can consider this snippet.

const dateStart = moment('2020-03-30');
const dateEnd = moment('2020-06-05');
let monthList = [];
while (dateEnd > dateStart || dateStart.format('M') === dateEnd.format('M')) {
   monthList.push(dateStart.format('MM'));
   dateStart.add(1,'month');
}

Here, you can push the month in the specific format. If you want to check date formats, you can check here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM