asp.net MVC

How to calculate the age from jQuery ui datepicker using c#?

How to calculate the age from jQuery ui datepicker using c#?, someone asked me to explain?
MVC

In this tutorial I will show how to calculate age from date of birth using c#. Here, I m using jquery ui datepicker, when the user selects the date and click the calculate button jquery ajax call the jsonResult method. This method will calculate the year, month and days of your age.

 

HTML View:  

 

<script src="https://code.jquery.com/jquery-2.2.4.min.js" ></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<h2>Calculate age using Birth Date in c#.</h2>
 
<input id="dtpBirthDate" autocomplete="off" class="input-group" />
<br />
<button type="button" id="btnCalculate"> Calculate Age</button>
<br />
<div id="divHtml"></div>
<script type="text/javascript">
    $(document).ready(function () {
        $("#dtpBirthDate").datepicker({
            dateFormat: 'dd-mm-yy'
        });
 
        $("#btnCalculate").click(function () {
            var date = $('#dtpBirthDate');
            var data = { date: date.val() };
            var json = JSON.stringify(data);
            $.ajax({
                url: '/AgeCalculator/GetDetails',
                type: "POST",
                data: json,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    $("#divHtml").html(result.calculatedAge);
                    return false;
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
            return false;
        });
    });
</script>

Controller Method:

 

[HttpPost]
        public JsonResult GetDetails(string date)
        {
            CultureInfo culture = new CultureInfo("es-ES");
            DateTime startTime = DateTime.Parse(date, culture);
            DateTime endTime = DateTime.Today;
            TimeSpan timespan = endTime.Subtract(startTime);
            var totalDays = timespan.TotalDays;
            var totalYears = Math.Truncate(totalDays / 365);
            var totalMonths = Math.Truncate((totalDays % 365) / 30);
            var remainingDays = Math.Truncate((totalDays % 365) % 30);
 
            var calculatedAge = string.Format("{0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);
 
            var json = Json(new { calculatedAge });
            return json;
        }
Output:
calculate age using c#

Post your comments / questions