To accomplish this task, the use of jQuery
is crucial. Refer to the example provided below for more clarity.
In addition to jQuery
, I have also incorporated moment.js
. The rationale behind this choice lies in the fact that when working with standard JavaScript date functions, numerous complications arise in a multi-device/browser setting. To circumvent these challenges, it is advisable to utilize a reliable and extensively tested JS date library. For additional information 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>
This explanation should provide some clarity on the matter.