Search code examples
javascriptfunctiondatecalendararr

Return the number of months between two dates as an array of strings


//So I have and array of months
 const months = [
     'January',
     'February',
     'March',
     'April',
     'May',
     'June',
     'July',
     'August',
     'September',
     'October',
     'November',
     'December'];

// If the input is startDate: 1-1-2019 & endDate: 3-15-21
// It should return an array like so:

const monthsBetweenDates = [January,February,March,April,May,June,July,August, September, October, November,December, January,February,March,April,May,June,July,August, September, October, November, December, January, Feb, March];

// The returned/new array should have all months between the start and end date above in Order, duplicated needed in order as well.

Thank you so much for your help and time. Please let me know if you have any further question.


Solution

  • Plain arithmetical solution


    Considering the goal, I'd say solving the task with basic math makes more sense, than dealing with the Date type.

    All you need is:

    • destructure date strings (m-d-yyyy) of start and end dates into start/end months and years (mStart, yStart, mEnd, yEnd):
    const [mStart, , yStart] = start.split('-'),
          [mEnd, , yEnd] = end.split('-') 
    
    • calculate total length of period (in months, including both start and end) as
    12*(yEnd-yStart)+(mEnd-mStart)+1}
    
    • return an array of corresponding length, where each item will be taken from the source month array shifted one position rotationally:
    months[(mStart-1+i)%months.length]
    

    You may find complete demo below:

    const startDate = '1-1-2019',
          endDate = '3-15-2021',
         
          monthsBetweenDates = (start,end) => {
            const months = ['January','February','March','April','May','June','July','August','September','October','November','December'],
                  [mStart, , yStart] = start.split('-'),
                  [mEnd, , yEnd] = end.split('-')             
            return Array.from(
              {length: 12*(yEnd-yStart)+(mEnd-mStart)+1},
              (_,i) => months[(mStart-1+i)%months.length]
            )
          }
          
    console.log(monthsBetweenDates(startDate,endDate))
    .as-console-wrapper{min-height:100%;}