0

For instance, the actual age it should return is 47... using this code it returns me 48. Am i doing the right way of applying the logic and calculating the age in days, months and year.

John Cooper
  • 7,343
  • 31
  • 80
  • 100
  • actual age return 47 for what input value? – Eineki Jun 27 '11 at 10:38
  • I'm not sure what the problem is, but here's an alternative posted by user CMS, who knows his Javascript: [Calculate age in JavaScript](http://stackoverflow.com/q/4060004) – Pekka Jun 27 '11 at 10:38
  • What is 12*30? It certainly isn't the number of days in a year. Some problems with your number of days in a month calculations at least... – Niklas Jun 27 '11 at 10:39
  • Exact duplicate of [codereview.SE question](http://codereview.stackexchange.com/questions/3142/need-tips-over-improving-this-javascript-code) – Raynos Jun 27 '11 at 10:46
  • 2
    by removing the sample code this doesn't make any sense.. – Lipis Jun 27 '11 at 12:50

3 Answers3

2

Assumption that 12 months times 30 days is a year - that's what's most wrong in here (that's 360 days, while in fact 1 year is close to 365.25 days on average).

What you should be doing, is calculating each segment separately:

var now = new Date();
var years = now.getFullYear()-formattedDate.getFullYear();
var months = now.getMonth()-formattedDate.getMonth();
var days = now.getDate()-formattedDate.getDate();

if (months < 0) {
    months += 12;
    years -= 1;
}

if (days < 0) {
    months -= 1;
    // now days here is a little trickier - we need the number of days in last month
    now.setTime(now.getTime() - now.getDate()*24*60*60*1000);
    days += now.getDate(); // <-- now is last day of last month now, so we know how many days there were and add this number
}
mkilmanas
  • 3,395
  • 17
  • 27
1

At first look a year is 365,25 days, not 30*12 = 360 (at least in the gregorian calendar)

Eineki
  • 14,773
  • 6
  • 50
  • 59
1

google: date diff js will help with examples.

Note:

  • Months have not 30 days!
  • Days (in some applications) have not 24 hours too, because of DST. Surprise!

P.S. ExtJS has very nice Date handling utils in it.

Pavel Koryagin
  • 1,479
  • 1
  • 13
  • 27