angulardategettime

getTime() in format 'day-month-year' (Angular)


In a DB I have a date of birth in format day-month-year (like this "12-07-1997, 13-07-1997"). I want to get an age and use function like this:

if (birthday) {
  let timeDiff = Math.abs(Date.now() - new Date(birthday).getTime());
  let age = Math.floor(timeDiff / (24 * 3600 * 1000) / 365.25);
  console.log(age + ' y.o.')
}

In first example it returns 22 y.o., but in case of 13-07-1997 I have NaN y.o.. I think its 'cause of format of the date. Any ideas how should I correctly use getTime() here?

Would be really grateful for any help!


Solution

  • new Date('13-07-1997') is getting Invalid Date , this the reason why you are getting NaN, Please try below code

      let birthdayString="13-07-1997";
      let dateParts = birthdayString.split("-");
      let newB=new Date(+dateParts[2], parseInt(dateParts[1]) - 1, +dateParts[0]);
      var ageDifMs = Date.now() - newB.getTime();
      var ageDate = new Date(ageDifMs); // miliseconds from epoch
      console.log("your age is" ,Math.abs(ageDate.getUTCFullYear() - 1970));