0

I want to get the number of years and months using Javascript, but I am not able to get to get them:

var date=new Date("2018-09-02")
document.body.innerHTML=calculateAge(date) //should print 1.1 year(s)

function calculateAge(date) { 
   var ageDifMs = Date.now() - date;
   var ageDate = new Date(ageDifMs); 
   return Math.abs(ageDate.getUTCFullYear() - 1970);
 }

View JSFiddle

I have researched a lot, but I wasn't able to find the right approach to print the difference in yy.mm format which is indicating year and months.

Sanjay
  • 1,226
  • 3
  • 21
  • 45
  • 2
    I'm confused. Years with months, but the expected output is decimal? – evolutionxbox Oct 04 '19 at 13:23
  • Expected output? – User863 Oct 04 '19 at 13:24
  • Possible duplicate of [Calculate age given the birth date in the format YYYYMMDD](https://stackoverflow.com/questions/4060004/calculate-age-given-the-birth-date-in-the-format-yyyymmdd) – frobinsonj Oct 04 '19 at 13:26
  • Your calculation makes little sense to begin with. `ageDifMs` is the number of seconds between your two dates - using that to initialize a new Date object `new Date(ageDifMs)` is completely and fundamentally wrong. – 04FS Oct 04 '19 at 13:44
  • 1
    There are already [*many duplicates*](https://stackoverflow.com/search?q=%5Bjavascript%5D+difference+between+dates+in+years+months). It seems you just want to format the result as years.months. You should clarify the rounding rule for month. – RobG Oct 04 '19 at 20:16
  • this script is worked for me.. https://jsfiddle.net/g1tj9s3m – Sanjay Oct 09 '19 at 08:36

2 Answers2

0

You should check the conversions first before asking... Here

function toYear(dateOne, dateTwo){
  var milToYear = 1000  * 60 * 60 * 24 * 365 // 1000 to 1 sec * 60 for 60 sec * 60 for min * 24 for hours   365 

  var difDate = dateOne.getTime() - dateTwo.getTime();
  var result  =  difDate / milToYear;
  console.log(result);
return result;
}

var date =  new Date();
var date2 = new Date('2018-09-02');
toYear(date, date2);
George Stavrou
  • 482
  • 5
  • 11
-1

var date = new Date("2018-09-02");
var age = calculateAge(date);
document.body.innerHTML = age;
 
function calculateAge(date) { 
  var dateNow = Date.now(); 
  
  // To calculate the time difference of two dates 
  var Difference_In_Time = dateNow - date.getTime(); 
  console.log("Difference_In_Time : " + Difference_In_Time);
  
  // To calculate the no. of days between two dates 
  var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
  
  console.log("Difference_In_Days: " + Difference_In_Days);
  // To calculate difference in Years
  
  var Difference_In_Years = Difference_In_Days / 365
  console.log("Difference_In_Years: " + Difference_In_Years);
  return Difference_In_Years;
}
rprakash
  • 500
  • 5
  • 10