0

I apologize if this question has been answered. I looked everywhere and could not make this work.

as of now, my code returns the number of days like the attached example, but I would like to get the result in this format --> 1 year, 5 months, 10 days.

Is there a better way to get at this result? This is the code that I have so far, all the help would be appreciated it. Here is a bin if it helps.

function reworkedInBetweenDays(year, month, day){
  
   var firstDate = new Date();
    var secondDate =  new Date(year, month-1, day);
 
    var diffDays;
    var startDate = firstDate.getTime();
    var endDate   = secondDate.getTime();
  
    diffDays = (startDate - endDate) / 1000 / 86400;
    diffDays = Math.round(diffDays - 0.5);

    return diffDays;
   
 }

 console.log(reworkedInBetweenDays(2014,09,21));
Lucky500
  • 677
  • 5
  • 17
  • 31

1 Answers1

1

function reworkedInBetweenDays(year, month, day) {

   var today = new Date();

   var fromdate = new Date(year, month - 1, day);

   var yearsDiff = today.getFullYear() - fromdate.getFullYear();
   var monthsDiff = today.getMonth() - fromdate.getMonth();
   var daysDiff = today.getDate() - fromdate.getDate();

   if (monthsDiff < 0 || (monthsDiff === 0 && daysDiff < 0))
      yearsDiff--;
   if (monthsDiff < 0)
      monthsDiff += 12;

   if (daysDiff < 0) {
      var fromDateAux = fromdate.getDate();
      fromdate.setMonth(fromdate.getMonth() + 1, 0);
      daysDiff = fromdate.getDate() - fromDateAux + today.getDate();
      monthsDiff--;
   }

   var result = [];

   if (yearsDiff > 0)
      result.push(yearsDiff + (yearsDiff > 1 ? " years" : " year"))
   if (monthsDiff > 0)
      result.push(monthsDiff + (monthsDiff > 1 ? " months" : " month"))
   if (daysDiff > 0)
      result.push(daysDiff + (daysDiff > 1 ? " days" : " day"))

   return result.join(', ');
   
   /* or as an object
   return {
      years: yearsDiff,
      months: monthsDiff,
      days: daysDiff
   }*/
}

console.log(reworkedInBetweenDays(2015, 2, 3));
console.log(reworkedInBetweenDays(2014, 9, 21));
console.log(reworkedInBetweenDays(2016, 1, 31));
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98