JavaScript Age Calcultor From Date Of Birth Example

Dec 10, 2021 . Admin



Hello Friends,

Now let's see example of how to use age calculator from date of birth example. We will check how to use age calculator from date of birth. This is a short guide on use age calculator from date of birth in javascript. Let's get started with how to use age calculator from date of birth in javascript.

Here i will give you many example how to use age calculator from date of birth using javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>JavaScript Age Calcultor From Date Of Birth Example - MyWebtuts.com</title>
    </head> 
    <body>  
        <h3>JavaScript Age Calcultor From Date Of Birth Example - MyWebtuts.com</h3>
        
        <script type="text/javascript">

            function calsAge(dob) { 
                var ageCalc = Date.now() - dob.getTime();
                var ageDate = new Date(ageCalc); 
              
                return Math.abs(ageDate.getUTCFullYear() - 1970);
            }

            document.write(calsAge(new Date(2001, 3, 4)));

        </script>
    </body>
</html>
Output :
20
Example : 2
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>JavaScript Age Calcultor From Date Of Birth Example - MyWebtuts.com</title>
    </head> 
    <body>  
        <h3>JavaScript Age Calcultor From Date Of Birth Example - MyWebtuts.com</h3>

        <script type="text/javascript">

            const getAge = (birthDateString) => {
                const today = new Date();
                const birthDate = new Date(birthDateString);
                const yearsDifference = today.getFullYear() - birthDate.getFullYear();

                if(today.getMonth() < birthDate.getMonth() || (today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())){
                    return yearsDifference - 1;
                }
                return yearsDifference;
            };

            document.write(getAge('2000-12-12'));
            
        </script>
    </body>
</html>
Output :
20

It will help you...

#Javascript