Home > Blockchain >  How to show months and year together in mvc.net
How to show months and year together in mvc.net

Time:11-08

I am making a calculator that calculates the age in years but I also want to calculate months Please help me with this Regard Thank you. I want my output like this for 22 years and 3 months. Here is my Jquery code I want to add months code in this code to show months as well as years.

 <h2>Index</h2> <html>

<body> <div > <label  asp-for="Dob">Birth date:</label> <div > <input asp-for="Dob" id="txtDOB" asp-format="{0:yyyy-MM-dd}"  placeholder="YYYY-MM-DD" /> </div> @{ // TODO: L09 Task 4d - Validation Message for Dob } </div>

\<div \>
    \<label  for="Age"\>Age:\</label\>
    \<div \>
        \<input type="text" id="age" asp-for="Age"  /\>
    \</div\>

\</div\>

</body>

</html> <script src="~/Scripts/jquery-3.4.1.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script>

<script>

$(document).ready(function () {
    $("#txtDOB").change(function () {
        var dob = $("#txtDOB").val();

        if (dob == null || dob == "") {

        } else {
            $("#age").val(getAge(dob));
        }

    });

    function getAge(birth) {
        ageMS = Date.parse(Date()) - Date.parse(birth);
        age = new Date();
        age.setTime(ageMS);
        ageYear = age.getFullYear() - 1970;

        return ageYear;
    }
});

</script>

CodePudding user response:

You can use this to get the difference in months (total months):

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months  = d2.getMonth();
    return months <= 0 ? 0 : months;
}

Use devision (by 12) to get the full years difference, then use modulo to get the remaining months.

var totalMonths = monthDiff(d1, d2);
var years = totalMonths / 12;
var months = totalMonths % 12;

Example fiddle: enter image description here

It will help you to implement as per your requirement.

  • Related