0

The line let dateInPlay = zzGetLastDateOfTheMonth(new Date(year, month + 1, 1)) is duplicated and I could not think of how to avoid that.

Thanks in advance for any improvements!

/**
 * Gets number of full months between dates
 *
 * @author me
 * @version 1.0
 * @since 2022/10/24
 * @param {Date} start date
 * @param {Date} end date
 * @return {number} number of months between dates
 */
function zzFullMonthsBetween(_startDate, _endDate) {
  let firstDate = zzGetFirstDateOfTheMonth(_startDate)
  let lastDate  = zzGetLastDateOfTheMonth(_endDate)
  if (lastDate > firstDate) {
    let numberOfMonths  = 1
    if (firstDate.getFullYear() == lastDate.getFullYear() && firstDate.getMonth() == lastDate.getMonth())
      return numberOfMonths
    let year = firstDate.getFullYear()
    let month = firstDate.getMonth()  
    if (month == 12)
    {
      year++
      month = 1
    }
    let dateInPlay = zzGetLastDateOfTheMonth(new Date(year, month + 1, 1))
    numberOfMonths++
    do {
      if (lastDate.getTime() == dateInPlay.getTime())
        return numberOfMonths
      else {
        numberOfMonths++
        let year = dateInPlay.getFullYear()
        let month = dateInPlay.getMonth()  
        if (month == 12)
        {
          year++
          month = 1
        }
        dateInPlay = zzGetLastDateOfTheMonth(new Date(year, month + 1, 1))
      }
    }
    while (lastDate !== dateInPlay);
  }
  return undefined
}
// function TESTzzFullMonthsBetween()
// {
//   let today = new Date()
//   let dates = [new Date('1/1/2022'), new Date('10/24/2022'), new Date('11/27/2022'), new Date('12/5/2022'), new Date('1/2/2023'), new Date('2/1/2023'), new Date('2/2/2024'), ]
//   for (let z = 0; z < dates.length; z++)
//     Logger.log(`${dates[z]}: ${zzFullMonthsBetween(today, dates[z])}`)
// }

function zzGetFirstDateOfTheMonth(_date)
{
  return new Date(_date.getFullYear(), _date.getMonth(), 1)
}
function zzGetLastDateOfTheMonth(_date)
{
  let year = _date.getFullYear()
  let month = _date.getMonth()
  if (month == 12)
  {
    year++
    month = 1
  }
  return zzAddOnDate(new Date(year, month + 1, 1), -1)
}
function zzAddOnDate(_date, _daysToAdd)
{
  var newDate = new Date(_date);
  newDate.setDate(newDate.getDate() + _daysToAdd);
  return newDate;
}
Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
Doug Barense
  • 391
  • 3
  • 8

0 Answers0