jQuery (JavaScript) to find Age from DOB!

Already I have written a PHP script for the same functionality. Here is the link:

PHP Script to find age from Date of Birth (DOB)

So this jQuery script is about finding the age from a given date (Date Of Birth).

<html>
<head>
	<title>jQuery - Find age from DOB</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
	<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
	<style>
		.error{color: red; }
	</style>
	<script type="text/javascript">
		$(function(){
			$('.dob').datepicker({
				showOn: 'button',
				showAnim: 'slideDown'
			});
			
			$('#find_age').click(function(){
				$('.error, .msg').text('');
				var dob = $('.dob').val();
				if(dob == ''){
					$('.error').text('Select DOB!');
				}else{
					dobDate = new Date(dob);
					nowDate = new Date();
					
					var diff = nowDate.getTime() - dobDate.getTime();
					
					var ageDate = new Date(diff); // miliseconds from epoch
					var age = Math.abs(ageDate.getUTCFullYear() - 1970);
					
					$('.msg').text(age+ ' Years');
				}
			});
		});
	</script>
</head>
<body>
	Enter DOB: <input type="text" class="dob" placeholder="mm/dd/yyyy" value="05/16/1987" />
	<input type="button" id="find_age" value="Find Age" />
	<p>Result: <span class="error"></span><span class="msg"></span></p>
</body>
</html>

In the above script i have used jQuery and jQuery UI both libraries.

See the demo:

demo

 

Leave a Comment

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

Scroll to Top