代码之家  ›  专栏  ›  技术社区  ›  user160820

javascript-年龄计算

  •  12
  • user160820  · 技术社区  · 14 年前

    有两个javascript日期,

    第一个是生日 第二个是从那个日期开始计算年龄的日期。

    最好的方法是什么?

    11 回复  |  直到 14 年前
        1
  •  13
  •   Mic    14 年前

    以下是一种方法:

    function getAge(d1, d2){
        d2 = d2 || new Date();
        var diff = d2.getTime() - d1.getTime();
        return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
    }
    console.log( getAge(new Date(1978, 10, 3)) );
    

    小心这个月。javascript从0开始计数。
    1978, 10, 3 指1978年11月3日

        2
  •  28
  •   Matt user129975    14 年前
    function calculateAge (birthDate, otherDate) {
        birthDate = new Date(birthDate);
        otherDate = new Date(otherDate);
    
        var years = (otherDate.getFullYear() - birthDate.getFullYear());
    
        if (otherDate.getMonth() < birthDate.getMonth() || 
            otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
            years--;
        }
    
        return years;
    }
    

    例子:

    var age = calculateAge("02/24/1991", "02/24/2010"); // Format: MM/DD/YYYY
    
        3
  •  4
  •   Dinesh Rabara    12 年前
    function getAge(dateString) {
      var now = new Date();
      var today = new Date(now.getYear(),now.getMonth(),now.getDate());
    
      var yearNow = now.getYear();
      var monthNow = now.getMonth();
      var dateNow = now.getDate();
    
      var dob = new Date(dateString.substring(6,10),
                         dateString.substring(0,2)-1,                   
                         dateString.substring(3,5)                  
                         );
    
      var yearDob = dob.getYear();
      var monthDob = dob.getMonth();
      var dateDob = dob.getDate();
      var age = {};
      var ageString = "";
      var yearString = "";
      var monthString = "";
      var dayString = "";
    
    
      yearAge = yearNow - yearDob;
    
      if (monthNow >= monthDob)
        var monthAge = monthNow - monthDob;
      else {
        yearAge--;
        var monthAge = 12 + monthNow -monthDob;
      }
    
      if (dateNow >= dateDob)
        var dateAge = dateNow - dateDob;
      else {
        monthAge--;
        var dateAge = 31 + dateNow - dateDob;
    
        if (monthAge < 0) {
          monthAge = 11;
          yearAge--;
        }
      }
    
      age = {
          years: yearAge,
          months: monthAge,
          days: dateAge
          };
    
      if ( age.years > 1 ) yearString = " years";
      else yearString = " year";
      if ( age.months> 1 ) monthString = " months";
      else monthString = " month";
      if ( age.days > 1 ) dayString = " days";
      else dayString = " day";
    
    
      if ( (age.years > 0) && (age.months > 0) && (age.days > 0) )
        ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
      else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) )
        ageString = "Only " + age.days + dayString + " old!";
      else if ( (age.years > 0) && (age.months == 0) && (age.days == 0) )
        ageString = age.years + yearString + " old. Happy Birthday!!";
      else if ( (age.years > 0) && (age.months > 0) && (age.days == 0) )
        ageString = age.years + yearString + " and " + age.months + monthString + " old.";
      else if ( (age.years == 0) && (age.months > 0) && (age.days > 0) )
        ageString = age.months + monthString + " and " + age.days + dayString + " old.";
      else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) )
        ageString = age.years + yearString + " and " + age.days + dayString + " old.";
      else if ( (age.years == 0) && (age.months > 0) && (age.days == 0) )
        ageString = age.months + monthString + " old.";
      else ageString = "Oops! Could not calculate age!";
    
      return ageString;
    }
    
    // A bit of jQuery to call the getAge() function and update the page...
    $(document).ready(function() {
      $("#submitDate").click(function(e) {
        e.preventDefault();
    
        $("#age").html(getAge($("input#date").val()));
    
      });
    });
    
    and HTML IS
    

    日期(年/月/日): 计算年龄

    年龄:7岁,1个月,15天。
        4
  •  2
  •   Frédéric Hamidi    14 年前

    将日期转换为自epoch以来的毫秒,使用 getTime() ,然后减去值并将结果转换回年份:

    const MS_PER_YEAR = 1000 * 60 * 60 * 24 * 365.2425;
    var years = Math.floor((dateNow.getTime() - dateThen.getTime()) / MS_PER_YEARS);
    
        5
  •  1
  •   Coin_op    14 年前

    最好的方法可能是将日期转换为时间戳,可能使用 parse() 如果日期是字符串。然后简单地减去数字并将新数字转换回日期,使用 new Date(milliseconds)

    但对于1970年1月1日之前的日期来说,这可能不太准确,因此可以使用另一种方法来减去日期、月份等。分开比较合适。

        6
  •  1
  •   Gabriele Petrioli    14 年前
    var birth = new Date('07/11/2003');
    var check = new Date();
    
    var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
    
    
    var ageInDays = (check - birth) / milliDay;
    
    var ageInYears =  Math.floor(ageInDays / 365 );
    

    例子 http://www.jsfiddle.net/gaby/XDKa3/1/

        7
  •  1
  •   Pascal Qyy    14 年前

    如果你在一个巨大的javascript项目中,你可能[使用需要使用]一个框架…

    Mootools More ,你有一个 Date Type 用一个 diff method 和A timeDiff method 这可以满足你的需要。

    它甚至 provide localisation !

        8
  •  0
  •   Gary    14 年前

    我已经修改了麦克风的响应,以允许今天是用户的生日。不同的是,您检查年龄的日期应设置为当天的午夜和/或当前日期应设置为23:59:59。例如,如果用户今天是18岁,则返回18。

    function getAge(d1){
        var now = new Date();
        var d2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
        var diff = d2.getTime() - d1.getTime();
        return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
    }
    console.log(getAge(new Date(1992, 10, 17, 0, 0, 0)));
    
        9
  •  0
  •   Shemeer M Ali    7 年前

    获取按当前年份计算的年龄

    calculateExp(birthDate) {
        birthDate = new Date(birthDate);
        var now = new Date();
        otherDate = new Date(now.getFullYear(),now.getMonth(),now.getDate());
        var years = (otherDate.getFullYear() - birthDate.getFullYear() );
    
    
        if (otherDate.getMonth() < birthDate.getMonth() || otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
            years--;
        }
    
        return years;
    }
    
        10
  •  0
  •   Sam G    7 年前
    function getAge(dateOfBirth, tillDate) {
        var dob = new Date(dateOfBirth);
        var endDt = new Date(tillDate) || new Date();
        return new Date(endDt.getTime() - dob.getTime()).getUTCFullYear() - 1970;
    }
    

    例子: console.log(getAge('1/1/2000', '1/1/2016')); // Format: MM/DD/YYYY

        11
  •  0
  •   vibs2006    5 年前

    下面是一个使用 力矩JS 图书馆现在很常见。只需将这个答案添加到许多其他答案中。

    var banner = $("#banner-message")
    var button = $("button")
    
    // handle click and add class
    button.on("click", function(){
      var inputValue = $("#txtInput").val();
      var age = parseInt(moment().diff(inputValue,'years',true));
      
    $("#spantext").html(age + ' years.');
      
    })
    body {
      background: #20262E;
      padding: 20px;
      font-family: Helvetica;
    }
    
    #banner-message {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      
      text-align: center;
      transition: all 0.2s;
      margin: 0 auto;
      width: 300px;
    }
    
    button {
      background: #0084ff;
      border: none;
      border-radius: 5px;
      padding: 8px 14px;
      font-size: 15px;
      color: #fff;
    }
    
    #banner-message.alt {
      background: #0084ff;
      color: #fff;
      margin-top: 40px;
      width: 200px;
    }
    
    #banner-message.alt button {
      background: #fff;
      color: #000;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <div id="banner-message">
      <p>Enter Date: <input type='text' id='txtInput' value='1981-12-25' /></p>
      <label>Age is : </label><span id='spantext'></span> <br/>
      <p><button>Calculate Age</button></p>
    </div>