How to convert days into human-readable years, months and days in JavaScript

2 Answers

0 votes
function splitDays(totalDays) {
  const start = new Date(1970, 0, 1);        // Jan 1, 1970
  const end   = new Date(start);
  end.setDate(start.getDate() + totalDays);

  let years  = end.getFullYear() - start.getFullYear();
  let months = end.getMonth()    - start.getMonth();
  let days   = end.getDate()     - start.getDate();

  // Normalize negative days
  if (days < 0) {
    months--;
    const prevMonth = new Date(end.getFullYear(), end.getMonth(), 0);
    days += prevMonth.getDate();
  }

  // Normalize negative months
  if (months < 0) {
    months += 12;
    years--;
  }

  return { years, months, days };
}

console.log(splitDays(452));



/*
run:

{ years: 1, months: 2, days: 28 }

*/

 



answered Dec 31, 2025 by avibootz
0 votes
function splitDays(totalDays) {
  const years  = Math.floor(totalDays / 365);
  totalDays   %= 365;

  const months = Math.floor(totalDays / 30);
  totalDays   %= 30;

  const days   = totalDays;

  return { years, months, days };
}

console.log(splitDays(452));



/*
run:

{ years: 1, months: 2, days: 27 }

*/

 



answered Dec 31, 2025 by avibootz

Related questions

...