JavaScript

Calculate age given the birth date in the format YYYYMMDD in Javascript

In this tutorial, we are going to see how to calculate the age of a person using their birth date as input in JavaScript.
 

Script to calculate the age from the birth date
<script type="text/javascript">
    function getAge(date) { 
        var diff = Date.now() - date.getTime();
        var age = new Date(diff); 

        return Math.abs(age.getUTCFullYear() - 1970);
    }

    alert(getAge(new Date(1995, 12, 6))); //Date(year, month, day)   
</script>

Output:

23

To get the person’s age in milliseconds, subtract the birth date (date.getTime()) from the current date (Date.now()). The Date.now() method returns the number of milliseconds since January 1, 1970.
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *