开发者

Whats wrong with the logic here in this code?

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.开发者_Python百科


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
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜