如何包含自动填充年龄的getFullMonth和getFullDate?

时间:2018-09-19 06:55:00

标签: javascript

我要在选择出生日期后自动填写年龄,我使用的是getFullYear。是否可以在选择出生日期时包含getMonth和getDate?这是我的代码。 Javascript

<script type = "text/javascript">
        $(document).ready(function () {
            var age = "";
            $('#dateofbirth').datepicker({
                onSelect: function (value, ui) {
                    var today = new Date();
                    age = today.getFullYear() - ui.selectedYear;
                    $('#myAge').val(age);
                },
                changeMonth: true,
                changeYear: true
            })
        })
    </script>

1 个答案:

答案 0 :(得分:0)

$(document).ready(function() {
    $('#dateofbirth').datepicker({
      onSelect: function (value, ui) {
        var selectedDate = new Date(ui.selectedYear, ui.selectedMonth, ui.selectedDay), //Convert value to date
            dateToday = new Date(), //Get the date today.
            age = Math.floor((dateToday - selectedDate) / 31536000000) //Get the difference of dates then convert to number of years.

        $('#age').val(age);
      },
      changeMonth: true,
      changeYear: true
    });
  });
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'></script>
<input id='dateofbirth'>
<input id='age'>

更新:

我使用(1000*60*60*24*365) = 31536000000而不是(1000*60*60*24*365.25) = 31557600000

每四年有1天的额外时间,因此,我们没有逐个循环,而是每年增加0.25天的费用。

$(document).ready(function() {
    $('#dateofbirth').datepicker({
      onSelect: function (value, ui) {
        var selectedDate = new Date(ui.selectedYear, ui.selectedMonth, ui.selectedDay), //Convert value to date
            dateToday = new Date(), //Get the date today.
            age = Math.floor((dateToday - selectedDate) / 31557600000) //Get the difference of dates then convert to number of years.

        $('#age').val(age);
      },
      changeMonth: true,
      changeYear: true
    });
  });
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'></script>
<input id='dateofbirth'>
<input id='age'>