1

How can I show years and month?

I need to calculate age based on the selected date of birth from the date picker.

But when selecting some date incorrect age displayed.

I have used jquery to calculate to find the age. Sometimes the age is not correct.

I need to show x years and x month old.

When I selecting date like 22-07-2012 show 6 years old.

The actual result is "7 years old"

 dob = new Date($("#DateOfBirth").val())
 var today = new Date();
 var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
 $('#txtAge').val(age + ' years old');
Jasmine
  • 25
  • 4

3 Answers3

0
dob = new Date($("#DateOfBirth").val())

var dobYear = dob.getFullYear();
var now = new Date(Date.now()).getFullYear();
var age = now - dobYear;
godot
  • 3,422
  • 6
  • 25
  • 42
0

The above problem can be solved using the below code:

First Store the date in a variable, and separate the day, year and month:

var mydate = $("#birth_date").val().toString();
var yearThen = parseInt(mydate.substring(0,4), 10);
var monthThen = parseInt(mydate.substring(5,7), 10);
var dayThen = parseInt(mydate.substring(8,10), 10);

then get today's date and the birth-date:

var today = new Date();
var birthday = new Date(yearThen, monthThen-1, dayThen);

After that, all that remains is the calculations:

var year_age = Math.floor(differenceInMilisecond / 31536000000);
var day_age = Math.floor((differenceInMilisecond % 31536000000) / 86400000);

var month_age = Math.floor(day_age/30);
day_age = day_age % 30;
if (isNaN(year_age) || isNaN(month_age) || isNaN(day_age)) {
        $("#exact_age").text("Invalid birthday - Please try again!");
    }
    else {
        $("#exact_age").html("You are<br/><span id=\"age\">" + year_age + " years " + 
    month_age + " months " + day_age + " days</span> old");
    }
0

JavaScript date object don't have this format DD-MM-YYYY, use this format YYYY-MM-DD, Check below code which gives your expected output.

function myFunction() {
  var input = $("#DateOfBirth").val();
  var dob = new Date(input);
  var today = new Date();
  var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
  $("#txtAge").html(age + ' years old');

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>

  <input value="2012-07-22" id="DateOfBirth" type='text' />
  <button onclick="myFunction()">Get Age</button>
  <br/>
  <label id="txtAge"></label>
</div>

I hope this will solve your problem.

Sagar Kulthe
  • 516
  • 3
  • 14