1

I have to check the age validation, so I have tried the following method for getting age:

let newDate = new Date(this.userDob);
var timeDiff = Math.abs(Date.now() - newDate);
let age = Math.floor((timeDiff / (1000 * 3600 * 24)) / 365);

here this.userDob is a string. How can I use this string to get age using javascript?

7
  • 1
    I don't think this question relates to angular, just to javascript data manipulation Commented Apr 6, 2017 at 10:20
  • 2
    Possible duplicate of Calculate age in JavaScript Commented Apr 6, 2017 at 10:20
  • @RadicalFanatic i have to use angular2. im using angular 2 for my app Commented Apr 6, 2017 at 10:20
  • 1
    @RahulBridge - in the code you posted, you're not using the angular framework. new Date(...) and Math.abs(...) and Math.floor(...) are pure javascript functions that don't require the angular library. Commented Apr 6, 2017 at 10:22
  • @RadicalFanatic how can i use this or how to get age from date ? Commented Apr 6, 2017 at 11:08

1 Answer 1

1

I have done it using like this,

var dob = //Here Im getting dob
var today = new Date();
var birthDate = new Date(dob);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
}

Now I'm able to check the age

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.