Age (+leap year) calculation in Javascript?

前端 未结 3 1294
-上瘾入骨i
-上瘾入骨i 2021-02-09 15:34

I\'ve read this question but there were many comments which some said it was accurate and some said it wasn\'t accurate.

Anyway I have this code which calc pers

3条回答
  •  深忆病人
    2021-02-09 16:21

    The way you calculate the difference between too dates will give you a result in days, and it does take into account leap years.

    However, your function is meant to return a value in years, so you need to convert your unit from days to years, this conversion needs the .242 in order to be exact, so it appears your logic is sound.

    Edit: In order to obtain a return similar to what is expected from an age calculator you have to get the day, month and year of both dates, use the days and months to check whether the day is after or before the other date, and then subtract the years and optionally add 1, for instance:

    function getAge(dateStr) {
      var cur = new Date();
      var tar = new Date(dateStr);
    
      // Get difference of year
      var age = cur.getFullYear() - tar.getFullYear();
    
      // If current month is > than birth month he already had a birthday
      if (cur.getMonth() > tar.getMonth()) {
         age ++;
      } 
      // If months are the same but current day is >= than birth day same thing happened 
      else if (cur.getMonth() == tar.getMonth() && cur.getDate() >= tar.getDate()) {
         age ++;
      }
    
      return age;
    }
    

    You can fiddle with the >= or compare hours to get more detailed, but this should be enough for most age calculation requirements.

    Essentially, using the .242 will give you a more exact result from a scientific point of view, however age calculation is not exact from a societies point of view.

提交回复
热议问题