How to calculate age from jquery datepicker?

筅森魡賤 提交于 2020-08-26 04:58:08

问题


I want to calculate age when date is selected by using jquery date picker. I added code below but it showing minus value if i select date like '19/03/2015','15/01/2015' or '19/03/2014' ,'31/12/2014'

  $(document).ready(function () 
{
 console.log($(document).width());           
     $('#patientDob').datepicker
    ({
        dateFormat: 'dd/mm/yy',
        changeMonth: true,
        changeYear: true,
        yearRange: '1900:2150',
        maxDate: new Date(),
        inline: true,

             onSelect: function() {
               var birthDay = document.getElementById("patientDob").value;
                var DOB = new Date(birthDay);
                var today = new Date();
                var age = today.getTime() - DOB.getTime();
                age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));

                document.getElementById('patientAge').value = age;
            }
     });  

});

回答1:


AFAIK The javascript Date requires yyyy/mm/dd, and you are sending:

 var DOB = new Date(birthDay); //  dateFormat: 'dd/mm/yy'

Change format to "yyyy/mm/dd" and will work ok.




回答2:


I have created this age calculator for my project using jQuery UI. and JavaScript function. you will get the exact result.

It it will calculate age and display as human readable. create a date field with ID 'datepicker'and import jquery and jquery ui . After that

Then just copy and paste the code to get the exact result.

output // 28 years 7 months 7 days

        $(function () {
        $("#datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
            showAnim: 'slideDown',
            dateFormat: 'yy-mm-dd'
        }).on('change', function () {
            var age = getAge(this);
           /* $('#age').val(age);*/
            console.log(age);
            alert(age);

        });

        function getAge(dateVal) {
            var
                birthday = new Date(dateVal.value),
                today = new Date(),
                ageInMilliseconds = new Date(today - birthday),
                years = ageInMilliseconds / (24 * 60 * 60 * 1000 * 365.25 ),
                months = 12 * (years % 1),
                days = Math.floor(30 * (months % 1));
            return Math.floor(years) + ' years ' + Math.floor(months) + ' months ' + days + ' days';

        }

});



来源:https://stackoverflow.com/questions/29137763/how-to-calculate-age-from-jquery-datepicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!