Abdulrahman A Alkhodairi Abdulrahman A Alkhodairi - 2 months ago 5x
HTML Question

Need correction or suggestion over javascript that calculate difference in between two dates

Age Calculations

I collect this JavaScript from many website; I would like to get age in between two different dates;

in this script or example I’m looking to show my daughter age;; Everything goes fine until her age passes 6 month,

The script rounds the age to the upper number which is
(ONE year in this case) , and
round down the month which shows months digit in minus.

Well, I would like the script to view years rounded to the lower number if it’s less than 365 days,
and months to be rounded up since the days less than 365 days.

<!-- Calculate Age -->
<script type="text/javascript">
var s = '2016-01-31T17:17:28.593Z';
var a = s.split(/[^0-9]/);
var d=new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5] );
var fromDate = new Date(d);
var toDate = new Date();

// current date format as mm-dd-yyyy
var Start_Date = new Date(d);
var sec = Start_Date.getSeconds();
var min = Start_Date.getMinutes();
var hr = Start_Date.getHours();
var dd = Start_Date.getDate();
var mm = Start_Date.getMonth()+1; //January is 0!
var yyyy = Start_Date.getFullYear();
var Start_Date = dd+'-'+mm+'-'+yyyy+'&nbsp at <span style="direction:ltr; color:red ;font-weight:700;">[&nbsp'+hr+ ":" +min+ ":" +sec+'&nbsp]</span>';
// End date format as mm-dd-yyyy
// Start_Date = str;
var differenceTravel = toDate.getTime() - fromDate.getTime();
// var months = Math.ceil (toDate.getMonth() - fromDate.getMonth() + (12 * (toDate.getFullYear() -
// 1 day = 86400000,
var Tyears = Math.round(differenceTravel/1000/60/60/24/365);
var Tmonths = Math.round((differenceTravel - (Tyears * 365*60*60*24*1000)) / (1000*60*60*24*30));
var Tdays = Math.round((differenceTravel - (Tyears *60*60*24*365*1000) - (Tmonths *60*60*24*30*1000))/ (86400000));
document.writeln('<div style="color:Blue">');
document.writeln('<li><span style="color:Navy">Seba Birthday:&nbsp;</span> ' + Start_Date +'</li>');
document.write('<li><span style="color:MediumVioletRed">Her age is:</span>&nbsp; '+ Tyears +'<span style="color:Green">&nbsp;year &nbsp; and &nbsp; </span>'+ Tmonths +'<span style="color:Green">&nbsp;months &nbsp; and &nbsp;</span>'+ Tdays +'<span style="color:Green">&nbsp;days</span></li>');
<!-- / good -->


If you want to round down, use Math.floor, not Math.round, which will round up or down depending on if the value is < or > than 0.5.