1

I am trying to make a website that tells you (in years, months, weeks, hours, minutes and seconds) how old you are. I have got all of them working apart from months and years. Once I get the months I will be able to get the years (hopefully), however I'm having trouble thinking of a way to get the months. For the others it was easy (once I had the seconds between the birth date and the current date I could just convert seconds to minutes, to hours, to days etc.), however for months I'm going to need to take into account the fact they are all different lengths, AND leap years (which currently does not affect the days either).

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
felixpackard
  • 579
  • 7
  • 21
  • @Fjpackard : See http://stackoverflow.com/questions/18913579/compare-two-date-formats-in-javascript-jquery – Roy M J Feb 07 '14 at 04:53

2 Answers2

1

Hope this helps you out

// Set the unit values in milliseconds.
 var msecPerMinute = 1000 * 60;
 var msecPerHour = msecPerMinute * 60;
 var msecPerDay = msecPerHour * 24;

// Set a date and get the milliseconds
 var date = new Date('6/15/1990');
 var dateMsec = date.getTime();

// Set the date to January 1, at midnight, of the specified year.
   date.setMonth(0);
   date.setDate(1);
   date.setHours(0, 0, 0, 0);

// Get the difference in milliseconds.
   var interval = dateMsec - date.getTime();

// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
   var days = Math.floor(interval / msecPerDay );
   interval = interval - (days * msecPerDay );

// Calculate the hours, minutes, and seconds.
   var hours = Math.floor(interval / msecPerHour );
   interval = interval - (hours * msecPerHour );

    var minutes = Math.floor(interval / msecPerMinute );
    interval = interval - (minutes * msecPerMinute );

    var seconds = Math.floor(interval / 1000 );

// Display the result.
   document.write(days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.");

 //Output: 164 days, 23 hours, 0 minutes, 0 seconds.
ajitksharma
  • 4,523
  • 2
  • 21
  • 40
0

Would you consider an external library? Check out http://momentjs.com/

You can easily do something like

date1.diff(date2, 'months')
Rami Enbashi
  • 3,526
  • 1
  • 19
  • 21