Reputation: 1828
I am developing a system which requires that you should be at least 18 years old to register.
For doing this validation i have implemented date difference in javascript in following way, but it is not accurate, is there any javascript function or other way to do this?
var d1=new Date(1985,1,28);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var years_old=milli/milliPerYear;
Upvotes: 0
Views: 2702
Reputation: 27233
Legally being at least 18 years old is not about the amount of time corresponding to the average duration of 18 years (years aren't always the same length). It is about the current date being after your 18th birth date. Hence, you should just add 18 to the year count on the birthdate and see if this is before or after the present date, e.g.
var birthDate = new Date(1985,1,28);
var today = new Date();
if (today >= new Date(birthDate.getFullYear() + 18, birthDate.getMonth(), birthDate.getDate())) {
// Allow access
} else {
// Deny access
}
You should do the same validation on the server side as well.
Note that this also handles people born on 29th February the correct way: in this case JavaScript will create a date object to represent the 1st March 18 years later.
Upvotes: 8
Reputation: 11983
I like http://momentjs.com/
<script src="moment.min.js"></script>
<script>
var dob = new moment([1985,1,28]);
var age = new.moment().diff(dob, 'years')
if (age >= 18) {
...
}
</script>
Upvotes: 1