This can be achieved with the help of jQuery
. See the example below.
Along with jQuery
I am using moment.js
. The reason for that is, when working with normal javascript date functions there are tons of issues in multi device / browser environment. To avoid that it is recommended to use a standard / well tested JS date library. More about Moment.JS
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
Your Age is: <span id="age">Pick a date</span>
<script>
$(document).ready(function() {
$( "#datepicker" ).datepicker();
$('#datepicker').change(function(){
var pickedDate = $(this).val();
var a = moment(pickedDate,"MM/DD/YYYY");
var b = moment(new Date());
var c = b.diff(a,'years',true);
$('#age').html(Math.floor(c) + ' year(s)');
});
} );
</script>
</body>
</html>
I hope this helps.