0

Basically I have to find out how old someone is in months, years and days. I have worked out the days and years but not the months as there're leap years and some months are different in length.

Here is my code

//Variables 
    var now = new Date();
    var totalDays = '';
    var totalMonths = '';
    var totalWeeks;
    var birthDate = new Date(document.getElementById('selYear').value, document.getElementById('selMonth').value, document.getElementById('selDay').value);
    var output = '';

//Total Days Old
var totalDays = Math.floor((now - birthDate) / 86400000);

//Total Weeks Old
totalWeeks = totalDays / 7;
totalWeeks = Math.round(totalWeeks);

//Total Months Old 
totalMonths = totalDays / 30;



//Total Years 
var totalYears = document.getElementById('selYear').value - now.getFullYear();
totalYears = Math.abs(totalYears);




//Outputs
output += 'You are ' + totalDays + ' days old';
output += '<br />You are ' + totalWeeks + ' weeks old';
output += '<br />You are ' + totalMonths + ' months old';
output += '<br />You are ' + totalYears + ' Years old';

I've thought of using if statements or a for loop and i've searched all of google and I can't find a way!

I have an application that asks the user for day, month and year. I have tested my current code (totalMonths = totalDays / 30) and it will get close to the totalMonths that it's suppose to be (I have checked an online site) and the date [1/1/1990] will fetch 302 while it should fetch 297 months

James111
  • 15,378
  • 15
  • 78
  • 121
  • Check [this](http://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript). – Brett Gregson Oct 23 '14 at 08:50

2 Answers2

0

Does this help you?

var d = new Date();
var n = d.getMonth() + 1;
var month = totalYears * 12  + n;
alert(month);

Just insert this after years and it should work.

elti musa
  • 710
  • 2
  • 7
  • 14
0

I suggest looking into Moment.js library . It makes working with dates stupid simple .

Example:

var me = moment("1983-11-19");
var today = moment();

me.diff(today, "days");    // -11296
me.diff(today, "months");  // -371
me.diff(today, "years");   // -30
Alexander
  • 12,424
  • 5
  • 59
  • 76
  • I've heard of this but as it's for a school assignment I have to use Javascript (no libarys). Moment.js would definitely be the way to go if this wasn't the case. – James111 Oct 23 '14 at 11:34