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

2 Answers

0 votes
type YMD = { years: number; months: number; days: number };

export function splitDays(totalDays: number): YMD {
  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 Jan 1 by avibootz
0 votes
type YMD = { years: number; months: number; days: number };

export function splitDays(totalDays: number): YMD {
  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 Jan 1 by avibootz

Related questions

...