I want to filter all the user who can register in my website. how can i filter the age of the registrant using jquery allowing 18 years old and above, but when the age is 13 to 17 years old they can register but they must check checkbox for parental consent. I am using a textbox with mm/dd/yyyy format.
My first thought:
Usage:
var age = getAge(new Date(1984, 7, 31));
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0));
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
Create 3 date objects - their birthday, a 13 year olds birthday and an 18 year olds birthday for them to be 18/13 today.
var input = document.get..
var dobArr = input.value.split("/");
var dob = new Date();
dob.setFullYear(dobArr[2], dobArr[0]-1, dobArr[1]);
var date18 = new Date();
date18.setFullYear(dobArr[2]-18);
var date13 = new Date();
date13.setFullYear(dobArr[2]-13);
if (dob.valueOf() >= date18.valueOf()) {
//i'm at least 18
} else if (dob.valueOf() >= date13.valueOf()) {
//i'm at least 13 but not 18
} else {
//i'm less than 13
}
Related
This question already has an answer here:
How to take the differences between two dates, depending on the date of birth [duplicate]
(1 answer)
Closed 2 years ago.
function test(val) {
year = parseInt(val.slice(0,2)); // get year
month = parseInt(val.slice(2,4)); // get month
date = val.slice(4,6); // get date
if (month > 40) { // For people born after 2000, 40 is added to the month.
year += 2000;
month -= 40;
} else {
year += 1900;
}
date = new Date(year, month-1, date, 0, 0);
date_now = new Date();
var diff =(date_now.getTime() - date.getTime()) / 1000;
diff /= (60 * 60 * 24);
diff = Math.abs(Math.floor(diff/365.25));
console.log(diff);
}
test("940911") // Should return 25
test("940910") // Should return 26
test("940909") // Should return 26
So If I'm born 1994.09.11 function should returns 25, Because 09.11 is tommorrow, but if I'm born at 1994.09.09, It should returns 26, because 09.09 was yesterday. I do not want to use libreries like moment.js etc.
Here the solution, anyway I suggest you to use moment.
So what about this solution?
Anyway the year? If 01 is 1901 or 2001 ?
function test(d){
let year = 1900+parseInt(d.slice(0,2));
let month = parseInt(d.slice(2,4));
let day = d.slice(4,6);
let yearNow = new Date().getFullYear();
let monthNow = new Date().getMonth() + 1;
let dayNow = new Date().getDate();
if (monthNow === month && dayNow < day || monthNow < month) {
return yearNow - year - 1;
} else {
return yearNow - year;
}
}
console.log(test("940911"))
console.log(test("940910"))
console.log(test("940909"))
I have a date array like this:
var dateArray = ["1965-12-29", "1902-11-04", "1933-10-21", "1983-10-16"];
What I would like to do is check/calculate each date of birth element to see if age is less than 110 years old based on year only. If age is greater than 110 years (also based on year only), then I would like to have this element remove/deleted from dateArray.
Basically, What I am trying to do is convert the following SQL code in JavaScript:
FROM TABLE X
WHERE TO_CHAR(DOB, 'YYYY') > (TO_CHAR(TO_DATE('2014/09/30', 'YYYY/MM/DD'), 'YYYY') - 110)
Many Thanks.
Use the .getFullYear() method of Date type:
for(var i=0;i<dateArray.length;i++)
{
var now = new Date();// or specify any date you want with new Date("2014/10/15");
var birth = new Date(dateArray[i]);
var age = now.getFullYear() - birth.getFullYear();
//then use the age var and test if it's bigger than 110
}
That should do it.
Here is how I would do it:
var dateArray = ["1965-12-29", "1902-11-04", "1933-10-21", "1983-10-16"];
dateArray = removeOldPeople(dateArray);
function removeOldPeople(dateArray){
//looping backwards because I delete items from array in loop
for(var i = dateArray.length -1 ; i >=0 ; i--){
var dateString = dateArray[i].split("-");
var year = dateString[0];
var month = parseInt(dateString[1])-1;
var day = dateString[2];
var age = calculateAge(day, month, year);
if(age >= 110) {
dateArray = dateArray.splice(i);
}
}
}
function calculateAge(birthMonth, birthDay, birthYear){
todayDate = new Date();
todayYear = todayDate.getFullYear();
todayMonth = todayDate.getMonth();
todayDay = todayDate.getDate();
age = todayYear - birthYear;
if (todayMonth < birthMonth - 1){
age--;
}
if (birthMonth - 1 == todayMonth && todayDay < birthDay){
age--;
}
return age;
}
I'm using this javascript to check if the age entered is older than 18.
function calculateDiffYear(date, month, year)
{
var cur = new Date();
var diff = Math.floor((cur.getTime() - new Date(year, month, date)) / (60 * 60 * 24 * 1000));
diff -= Math.floor((cur.getFullYear() - year) / 4);
return diff / 365;
}
function checkBorn(sender)
{
var root = sender.form;
var date = root.elements['date'].value;
var month = root.elements['month'].value - 1;
var year = root.elements['year'].value;
if (!isValidDate(date, month, year) || calculateDiffYear(date, month, year) < 18) return false;
return true;
}
If works almost right, except for, if we are in a leap year, it gives older than 18 to a person who becomes 18 tomorrow, at least in the tests I'm doing with today date and changing to las year. I tryed adding this but no luck:
if ($('#leap').val()) divider = 366;
else divider = 365;
return diff / divider;
Do you know how can I solve it?
Thank you
If I wanted to test if a particular date was more than 18 years ago I'd do something like this:
function meetsMinimumAge(birthDate, minAge) {
var tempDate = new Date(birthDate.getFullYear() + minAge, birthDate.getMonth(), birthDate.getDate());
return (tempDate <= new Date());
}
if (meetsMinimumAge(new Date(year, month, date), 18)) {
// is OK, do something
} else {
// too young - error
}
Essentially this takes the supplied birthday, adds 18 to it, and checks if that is still on or before today's date.
My age-checking code goes something like this:
function checkAge(dateofbirth) {
var yd, md, dd, now = new Date();
yd = now.getUTCFullYear()-dateofbirth.getUTCFullYear();
md = now.getUTCMonth()-dateofbirth.getUTCMonth();
dd = now.getUTCDate()-dateofbirth.getUTCDate();
if( yd > 18) return true;
if( md > 0) return true;
return dd >= 0;
}
Basically, if the year difference is 19 or more, then they must be over 18.
Otherwise, if the current month is past the month of birth, they are 18 and a few months old.
Otherwise, if the current day is greater than or equal to the day of birth, they are 18 and a few days old (or it is their 18th birthday).
This works regardless of leap years and is much more efficient than your current code.
You can use moment.js to validate it:
var yourDate = year.toString() + "/" + month.toString() + "/" day.toString();
var date = moment(yourDate, "YYYY/MM/DD"); // There are other formats!
var years = moment().diff(date, 'years', false);
if(years >= 18){
return true;
}
return false;
I am doing validation for Driver's Date of birth, it should be minimum of 18 from the current date.
var Dates = $get('<%=ui_txtDOB.ClientID %>');
var Split = Dates.value.split("/");
if (parseInt(Split[2]) > 1993)
{
alert("DOB year should be less than 1993");
Dates.focus();
return false;
}
I am using this above JavaScript validation for checking a person's DOB above 18, but it is not correct. I need to check with today's date and it should be above 18. How can I compare and check with the current date?
I think a better alternative would be to calculate the age of the user, and use that in your if statement.
See this SO answer on how to do just that:
Calculate age in JavaScript
Try this.
var enteredValue = $get('<%=ui_txtDOB.ClientID %>');;
var enteredAge = getAge(enteredValue.value);
if( enteredAge > 18 ) {
alert("DOB not valid");
enteredValue.focus();
return false;
}
Using this function.
function getAge(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--;
}
return age;
}
Demo here: http://jsfiddle.net/codeandcloud/n33RJ/
<script>
function dobValidate(birth) {
var today = new Date();
var nowyear = today.getFullYear();
var nowmonth = today.getMonth();
var nowday = today.getDate();
var b = document.getElementById('<%=TextBox2.ClientID%>').value;
var birth = new Date(b);
var birthyear = birth.getFullYear();
var birthmonth = birth.getMonth();
var birthday = birth.getDate();
var age = nowyear - birthyear;
var age_month = nowmonth - birthmonth;
var age_day = nowday - birthday;
if (age > 100) {
alert("Age cannot be more than 100 Years.Please enter correct age")
return false;
}
if (age_month < 0 || (age_month == 0 && age_day < 0)) {
age = parseInt(age) - 1;
}
if ((age == 18 && age_month <= 0 && age_day <= 0) || age < 18) {
alert("Age should be more than 18 years.Please enter a valid Date of Birth");
return false;
}
}
</script>
After looking at various methods of doing this, I decided the simplest way was to encode the dates as 8-digit integers. You can then subtract today's code from the DOB code and check if it's greater than or equal to 180000.
function isOverEighteen(year, month, day) {
var now = parseInt(new Date().toISOString().slice(0, 10).replace(/-/g, ''));
var dob = year * 10000 + month * 100 + day * 1; // Coerces strings to integers
return now - dob > 180000;
}
let TODAY = new Date(Date.now());
let EIGHTEEN_YEARS_BACK = new Date(new Date(TODAY).getDate() + "/" + new Date(TODAY).getMonth() + "/" + (new Date(TODAY).getFullYear() - 18));
let USER_INPUT = new Date("2003/12/13");
// Validate Now
let result = EIGHTEEN_YEARS_BACK > USER_INPUT // true if over 18, false if less than 18
I think this is the closest possible way to check.
My approach is to find the date 18 (or any number) years ago from today, then see if that's after (greater) than their dob. By setting all values to date objects it makes the comparison easy.
function is_of_age(dob, age) {
// dates are all converted to date objects
var my_dob = new Date(dob);
var today = new Date();
var max_dob = new Date(today.getFullYear() - age, today.getMonth(), today.getDate());
return max_dob.getTime() > my_dob.getTime();
}
Because the Date object can parse strings in a variety of formats, You don't have to worry too much about where dob is coming from. Simply call is_of_age("1980/12/4", 18); or is_of_age("2005-04-17", 13); or basically any string format or numeric that can be parsed as a Date parameter.
My favourite approach is this one:
var dateOfBirth = new Date("02/23/1900");
// calculate difference between now and the dateOfBirth (in milliseconds)
var differenceMs = Date.now() - dateOfBirth.getTime();
// convert the calculated difference in date format
var dateFromEpoch = new Date(differenceMs);
// extract year from dateFromEpoch
var yearFromEpoch = dateFromEpoch.getUTCFullYear();
// calculate the age of the user
var age = Math.abs(yearFromEpoch - 1970);
console.log("Age of the user: " + age + " years")
You can use the below:
var birthDate = new Date("2018-06-21");
var birthDate1 = new Date("1975-06-21");
function underAgeValidate(birthday) {
const diff = Date.now() - birthday.getTime();
const ageDate = new Date(diff);
let age = Math.abs(ageDate.getUTCFullYear() - 1970);
return age < 18;
};
console.log(underAgeValidate(birthDate));
console.log(underAgeValidate(birthDate1));
I'm passing my calendar selected date of birth to following JS function for calculating Age:
var DOBmdy = date.split("-");
Bdate = new Date(DOBmdy[2],DOBmdy[0]-1,DOBmdy[1]);
BDateArr = (''+Bdate).split(' ');
//document.getElementById('DOW').value = BDateArr[0];
Cdate = new Date;
CDateArr = (''+Cdate).split(" ");
Age = CDateArr[3] - BDateArr[3];
Now, lets say, input age is: 2nd Aug 1983 and age count comes: 28, while as August month has not been passed yet, i want to show the current age of 27 and not 28
Any idea, how can i write that logic, to count age 27 perfectly with my JS function.
Thanks !
Let birth date be august 2nd 1983, then the difference in milliseconds between now an that date is:
var diff = new Date - new Date('1983-08-02');
The difference in days is (1 second = 1000 ms, 1 hour = 60*60 seconds, 1 day = 24 * 1 hour)
var diffdays = diff / 1000 / (60 * 60 * 24);
The difference in years (so, the age) becomes (.25 to account for leapyears):
var age = Math.floor(diffdays / 365.25);
Now try it with
diff = new Date('2011-08-01') - new Date('1983-08-02'); //=> 27
diff = new Date('2011-08-02') - new Date('1983-08-02'); //=> 28
diff = new Date('2012-08-02') - new Date('1983-08-02'); //=> 29
So, your javascript could be rewritten as:
var Bdate = new Date(date.split("-").reverse().join('-')),
age = Math.floor( ( (Cdate - Bdate) / 1000 / (60 * 60 * 24) ) / 365.25 );
[edit] Didn't pay enough attention. date.split('-') gives the array [dd,mm,yyyy], so reversing it results in[yyyy,mm,dd]. Now joining that again using '-', the result is the string 'yyyy-mm-dd', which is valid input for a new Date.
(new Date() - new Date('08-02-1983')) / 1000 / 60 / 60 / 24 / 365.25
That will get you the difference in years, you will occasionally run into off-by-one-day issues using this.
May be this works:
var today = new Date();
var d = document.getElementById("dob").value;
if (!/\d{4}\-\d{2}\-\d{2}/.test(d)) { // check valid format
return false;
}
d = d.split("-");
var byr = parseInt(d[0]);
var nowyear = today.getFullYear();
if (byr >= nowyear || byr < 1900) { // check valid year
return false;
}
var bmth = parseInt(d[1],10)-1;
if (bmth<0 || bmth>11) { // check valid month 0-11
return false;
}
var bdy = parseInt(d[2],10);
if (bdy<1 || bdy>31) { // check valid date according to month
return false;
}
var age = nowyear - byr;
var nowmonth = today.getMonth();
var nowday = today.getDate();
if (bmth > nowmonth) {age = age - 1} // next birthday not yet reached
else if (bmth == nowmonth && nowday < bdy) {age = age - 1}
alert('You are ' + age + ' years old');
I just had to write a function to do this and thought'd I'd share.
This is accurate from a human point of view! None of that crazy 365.2425 stuff.
var ageCheck = function(yy, mm, dd) {
// validate input
yy = parseInt(yy,10);
mm = parseInt(mm,10);
dd = parseInt(dd,10);
if(isNaN(dd) || isNaN(mm) || isNaN(yy)) { return 0; }
if((dd < 1 || dd > 31) || (mm < 1 || mm > 12)) { return 0; }
// change human inputted month to javascript equivalent
mm = mm - 1;
// get today's date
var today = new Date();
var t_dd = today.getDate();
var t_mm = today.getMonth();
var t_yy = today.getFullYear();
// We are using last two digits, so make a guess of the century
if(yy == 0) { yy = "00"; }
else if(yy < 9) { yy = "0"+yy; }
yy = (today.getFullYear() < "20"+yy ? "19"+yy : "20"+yy);
// Work out the age!
var age = t_yy - yy - 1; // Starting point
if( mm < t_mm ) { age++;} // If it's past their birth month
if( mm == t_mm && dd <= t_dd) { age++; } // If it's past their birth day
return age;
}