N
N
NaN2019-05-28 13:52:36
JavaScript
NaN, 2019-05-28 13:52:36

How to deal with periods using moment.js?

To work with dates, moment.js is used (site on vue.js).
There is a dropdown with a choice of time interval (Example: 2019, 2020, 2019-2020, 2018-2019, 2018-2020). After the required period is selected, an object is formed with the start and end dates of this period:

currentYearPeriod: {
    endYear:"2020-01-01T05:00:00+05:00"
    startYear:"2019-01-01T05:00:00+05:00"
}

This information is then passed to the calendar component.
The goal is to get a calendar for a given period (there will be 12/24 or more cards with months (name, dates, days of the week) on the page).
How can I get an array of objects of months included in a given period? Example:
months: [
    {
        name: 'Январь',
        year: '2019',
        days: [
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
           18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
         ],
    },
],

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-05-28
@KornevaViktoria

const
  start = moment(currentYearPeriod.startYear),
  end = moment(currentYearPeriod.endYear),
  months = [];

for (; start < end; start.add(1, 'day')) {
  const [ year, name, day ] = start.format('YYYY.MMMM.D').split('.');
  let m = months[months.length - 1];
  if (!m || m.name !== name) {
    months.push(m = {
      year,
      name,
      days: [],
    });
  }
  m.days.push(+day);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question