Javascript - Age Verification - javascript

Hey javascript masters,
Attempting to create an age verification page to a client's site. Code below is not functioning as it doesn't matter what year you select, it will still allow you to enter the site. Not sure what I should be looking at to correct.
Any help is appreciated.
<script type="text/javascript"><!--
function checkAge(f){
var dob=new Date();
var date=dob.getDate();
var month=dob.getMonth() + 1;
var year=dob.getFullYear();
var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);
var cmbday=parseInt(document.getElementById("cmbday").options[document.getElementById("cmbday").selectedIndex].value);
var cmbyear=parseInt(document.getElementById("cmbyear").options[document.getElementById("cmbyear").selectedIndex].value);
age=year-cmbyear;
if(cmbmonth>month){age--;}
else{if(cmbmonth==month && cmbday>=date){age--;}}
if(cmbmonth==0){alert("You must enter the month you were born in.");return false;}
else if(cmbday==0){alert("You must enter the day you were born on.");return false;}
else if(cmbyear==2005){alert("You must enter the year you were born in.");return false;}
else if(age<13){alert("You are unable to view this site!");location.replace("http://www.dharmatalks.org");return false;}
else{return true;}
}
// --></script>

Calculating age in years, months and days is a bit trickier than it should be due to the differences in month and year lengths. Here's a function that will return the difference between two dates in years, months, days, hours, minutes and seconds.
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
var timeDiff, years, months, days, hours, minutes, seconds;
// Get estimate of year difference
years = e.getFullYear() - s.getFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
}
// Get estimate of months
months = e.getMonth() - s.getMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setMonth(s.getMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setFullYear(s.getFullYear() + years);
s.setMonth(s.getMonth() + months);
}
// Get remaining time difference, round to next full second
timeDiff = (e - s + 999) / 1e3 | 0;
days = timeDiff / 8.64e4 | 0;
hours = (timeDiff % 8.64e4) / 3.6e3 | 0;
minutes = (timeDiff % 3.6e3) / 6e1 | 0;
seconds = timeDiff % 6e1;
return [years, months, days, hours, minutes, seconds];
}
You can abbreviate the above just after the year part and return just that if you want.
Note that in your code:
var cmbmonth=parseInt(document.getElementById("cmbmonth").options[document.getElementById("cmbmonth").selectedIndex].value);
can be:
var cmbmonth = document.getElementById("cmbmonth").value;
There is no need for parseInt, the Date constructor will happily work with string values. If you have used calendar month numbers for the values (i.e. Jan = 1) then subtract 1 before giving it to the Date constructor, but simpler to use javascript month indexes for the values (i.e. Jan = 0).
You can then do:
var diff = dateDifference(new Date(cmbyear, cmbmonth, cmbdate), new Date());
if (diff[0] < 18) {
// sorry, under 18
}

Related

Javascript to count the number of days for a specific month between two dates [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed last month.
I am new to javascript.
I have specific month columns (9/30/2022, 10/31/2022,11/30/2022). I have a contract with a start date and end date (spanning multiple months).
I need to determine the number of days the contract was active for a specific month column.
Example:
Contact Start Date: 09/15/2022
Contract End Date: 10/24/2022
Number of days the contract was active in Sept 2022 is 16.
I found the code below that gives me the contract period broken down for each month (i.e.) **9 - 17; 10 - 23; **
Thank you in advance for any assistance.
I found this code
function getDays() {
var dropdt = new Date(document.getElementById("arr").value);
var pickdt = new Date(document.getElementById("dep").value);
var result = "";
for (var year = dropdt.getFullYear(); year <= pickdt.getFullYear(); year++) {
var firstMonth = (year == dropdt.getFullYear()) ? dropdt.getMonth() : 0;
var lastMonth = (year == pickdt.getFullYear()) ? pickdt.getMonth() : 11;
for (var month = firstMonth; month <= lastMonth; month++) {
var firstDay = (year === dropdt.getFullYear() && month === firstMonth) ? dropdt.getDate() : 1;
var lastDay = (year === pickdt.getFullYear() && month === lastMonth) ? pickdt.getDate() : 0;
var lastDateMonth = (lastDay === 0) ? (month + 1) : month
var firstDate = new Date(year, month, firstDay);
var lastDate = new Date(year, lastDateMonth, lastDay);
result += (month + 1) + " - " + parseInt((lastDate - firstDate) / (24 * 3600 * 1000) + 1) + "; ";
}
}
return result;
}
function cal() {
if (document.getElementById("dep")) {
document.getElementById("number-of-dates").value = getDays();
}
Calculate
`
The following snippet will generate an object res with the keys being zero-based month-indexes ("8" is for September, "9" for October, etc.) and the values are the number of days for each of these months:
const start=new Date("2022-09-15");
const end=new Date("2022-11-24");
let nextFirst=new Date(start.getTime()), month, days={};
do {
month=nextFirst.getMonth();
nextFirst.setMonth(month+1);nextFirst.setDate(1);
days[month]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
start.setTime(nextFirst.getTime());
} while(nextFirst<end)
console.log(days);
This can be extended into a more reliable function returning a year-month combination:
function daysPerMonth(start,end){
let nextFirst=new Date(start.getTime()), year, month, days={};
do {
year=nextFirst.getFullYear();
month=nextFirst.getMonth();
nextFirst.setMonth(month+1);nextFirst.setDate(1);
days[`${year}-${String(1+month).padStart(2,"0")}`]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
start.setTime(nextFirst.getTime());
} while(nextFirst<end)
return days;
}
[["2022-09-15","2022-11-24"],["2022-11-29","2023-02-04"]].forEach(([a,b])=>
console.log(daysPerMonth(new Date(a),new Date(b))));
Managing and calculating dates, times, and date-times are notoriously finicky in javascript and across browsers. Rather than trying to define your own logic for this use the famous Moment.js library.
In particular to calculate the length between two dates you can utilize the diff function between two moments
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 25]);
var diff = a.diff(b, 'days') // 1
console.log(diff);
<script src="https://momentjs.com/downloads/moment.js"></script>
The supported measurements are years, months, weeks, days, hours, minutes, and seconds.

How to calculate days between two date excluding weekends in angularjs? [duplicate]

This question already has answers here:
Find day difference between two dates (excluding weekend days)
(13 answers)
Closed 3 years ago.
In my application i have two date picker as start date and end date. when user choose start and end date the system will show the days between two dates but excluding the saturday and sunday. How to calculate it by using angularjs?
Does something like this work:
var startDate = new Date("01-10-2020");
var endDate = new Date("01-20-2020");
var nextDay = new Date(startDate);
var cnt = 0;
do {
/*if (nextDay.getDay() >= 1 && nextDay.getDay() <= 5) {
cnt = cnt + 1;
}*/
cnt += (nextDay.getDay() >= 1 && nextDay.getDay() <= 5) ? 1 : 0;
nextDay.setDate(nextDay.getDate() + 1);
} while (nextDay <= endDate);
console.log("Number of week days between " + startDate + " and " + endDate + " = " + cnt);
Here is the fiddler.
You don't want to do an expensive loop over every day to see whether it is Saturday or Sunday. The logic should be as follows:
Work in UTC so we don't need to worry about time zone
Calculate total number of calendar weeks. In a single calendar week, there are guaranteed to be 5 weekdays (not weekends == SAT || SUN)
Calculate the remainder of days. This will be added to the calculation later.
Determine the "finalAdjustment" by seeing if the remainder falls on weekend days.
The number of weekdays is (5 * numWeeks) + remainderDays + finalAdjust
(function() {
"use strict";
var SUN = 0;
var MON = 1;
var TUE = 2;
var WED = 3;
var THU = 4;
var FRI = 5;
var SAT = 6;
function isWeekendDay(day) {
return day === SAT || day === SUN;
}
function numberWeekDays(start, end) {
var numCalendarDays = (end - start) / 1000 / 60 / 60 / 24;
var numWeeks = Math.floor(numCalendarDays / 7);
// Potential days to add on to the number of full calendar
// weeks. This will be adjusted by "finalAdjust"
var remainderDays = numCalendarDays % 7;
// Adjustments for start and end dates being on a weekend
// ----------------------------
// Start at one because the same day should count as 1
// but number of days between same day is 0 based on
// arithmetic above.
// Change this to 0 if you don't want end date inclusive...
var finalAdjust = 1;
var startDay = start.getUTCDay();
var endDay = end.getUTCDay();
// On a weekend, so adjust by subtracting 1
if (isWeekendDay(startDay)) {
finalAdjust--;
}
// On a weekend, so adjust by subtracting 1
if (isWeekendDay(endDay)) {
finalAdjust--;
}
// This accounts for subtracting an extra weekend when starting
// at the beginning of a weekend (e.g. Saturday into Monday)
// The end day cannot also be on a weekend based on week modular division (mod 7)
if (startDay === SAT && remainderDays > 2) {
finalAdjust--;
}
// ---------------------------
// For every full calendar week there are 5 week days
// Use that number with the remainderDays and finalAdjust above
// to arrive at the answer.
var numWeekDays = (5 * numWeeks) + remainderDays + finalAdjust;
return numWeekDays;
}
// Test cases
// Assume that the start and end dates are inclusive
// 2020-01-01 to 2020-01-01 is one day
// 2020-01-01 to 2020-01-02 is two days
// ----------------------
// A Wednesdday
var start = new Date("2020-01-08");
// A Saturday
var end = new Date("2020-02-01");
// Expected answer: 18
console.log(numberWeekDays(start, end));
// A Saturday
start = new Date("2020-01-05");
// A Monday
end = new Date("2020-01-31");
// Expected answer: 20
console.log(numberWeekDays(start, end));
// Weekday to weekday Tuesday to
start = new Date("2020-01-07");
end = new Date("2020-01-16");
// Expected: 8
console.log(numberWeekDays(start, end));
// Same week: Mon-Wed
start = new Date("2020-01-06");
end = new Date("2020-01-08");
// Expected answer: 3
console.log(numberWeekDays(start, end));
// Same day
start = new Date("2020-01-08");
end = new Date("2020-01-08");
// Expect: 1
console.log(numberWeekDays(start, end));
// Weekend only
start = new Date("2020-01-04");
end = new Date("2020-01-05");
// Expect: 0;
console.log(numberWeekDays(start, end));
// ------------------
}());
As others have stated, a date library like moment is useful here because it gives you a lot of utility functions for working with dates and durations.

Trouble subtracting day from date in Sheets Script

I have written the following code and cannot figure out why it is not working in my Google Sheet:
function WEEKOF(myDay, myDate) {
var wkDate = new Date(myDate);
var StartDate = new Date();
StartDate.setDate(wkDate.getDate()-myDay);
return StartDate;
}
=WEEKOF(Weekday(A1), A1)
Cell A1 contains: 05/01/2016
Return: 7/26/2017
I'm expecting the return to be: 04/29/2016
Difference in Days,Hours,Minutes and Seconds
var adayinmilliseconds=24*60*60*1000;
var differenceBetweenTwoDatesInDays = Math.floor((date1.valueOf()-date2.valueOf())/adayinmilliseconds);
A Date Difference Function that output days, hours, minute and seconds. From the MDN Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC. The method of time() and valuOf() both provide us the the primitive value of dates ie the number of milliseconds from some date in the past. Yes, it can be quite a large number but in the end with a little simple arithmetic Math.floor(), /, % you end up with an easy calculation. You can change the output to an array or an object depending upon your requirements.
function calcTimeDifference(Start,End)
{
if(Start && End)
{
var second=1000;
var minute=60*second;
var hour=minute*60;
var day=hour*24;
var t1=new Date(Start).valueOf();
var t2=new Date(End).valueOf();
var d=t2-t1;
var days=Math.floor(d/day);
var hours=Math.floor(d%day/hour);
var minutes=Math.floor(d%day%hour/minute);
var seconds=Math.floor(d%day%hour%minute/second);
return 'dd:hh:mm:ss\n' + days + ':' + hours + ':' + minutes + ':' + seconds;
}
else
{
return 'Invalid Inputs';
}
}

exclude weekends in javascript date calculation

I have two sets of codes that work. Needed help combining them into one.
This code gets me the difference between two dates. works perfectly:
function test(){
var date1 = new Date(txtbox_1.value);
var date2 = new Date(txtbox_2.value);
var diff = (date2 - date1)/1000;
var diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
txtbox_3.value = days + "." + hrs; }
source for the above code
The code below by #cyberfly appears to have the answer of excluding sat and sun which is what i needed. source. However, its in jquery and the above code is in JS. Therefore, needed help combining as i lacked that knowledge :(
<script type="text/javascript">
$("#startdate, #enddate").change(function() {
var d1 = $("#startdate").val();
var d2 = $("#enddate").val();
var minutes = 1000*60;
var hours = minutes*60;
var day = hours*24;
var startdate1 = getDateFromFormat(d1, "d-m-y");
var enddate1 = getDateFromFormat(d2, "d-m-y");
var days = calcBusinessDays(new Date(startdate1),new Date(enddate1));
if(days>0)
{ $("#noofdays").val(days);}
else
{ $("#noofdays").val(0);}
});
</script>
EDIT
Made an attempt at combining the codes. here is my sample. getting object expected error.
function test(){
var date1 = new Date(startdate.value);
var date2 = new Date(enddate.value);
var diff = (date2 - date1)/1000;
var diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
var startdate1 = getDateFromFormat(startdate, "dd/mm/yyyy hh:mm");
var enddate1 = getDateFromFormat(enddate, "dd/mm/yyyy hh:mm");
days = calcBusinessDays(new Date(startdate1),new Date(enddate1));
noofdays.value = days + "." + hrs; }
start: <input type="text" id="startdate" name="startdate" value="02/03/2015 00:00">
end: <input type="text" id="enddate" name="enddate" value="02/03/2015 00:01">
<input type="text" id="noofdays" name="noofdays" value="">
When determining the number of days between two dates, there are lots of decisions to be made about what is a day. For example, the period 1 Feb to 2 Feb is generally one day, so 1 Feb to 1 Feb is zero days.
When adding the complexity of counting only business days, things get a lot tougher. E.g. Monday 2 Feb 2015 to Friday 6 February is 4 elapsed days (Monday to Tuesday is 1, Monday to Wednesday is 2, etc.), however the expression "Monday to Friday" is generally viewed as 5 business days and the duration Mon 2 Feb to Sat 7 Feb should also be 4 business days, but Sunday to Saturday should be 5.
So here's my algorithm:
Get the total number of whole days between the two dates
Divide by 7 to get the number of whole weeks
Multiply the number of weeks by two to get the number of weekend days
Subtract the number of weekend days from the whole to get business days
If the number of total days is not an even number of weeks, add the numbe of weeks * 7 to the start date to get a temp date
While the temp date is less than the end date:
if the temp date is not a Saturday or Sunday, add one the business days
add one to the temp date
That's it.
The stepping part at the end can probably be replaced by some other algorithm, but it will never loop for more than 6 days so it's a simple and reasonably efficient solution to the issue of uneven weeks.
Some consequences of the above:
Monday to Friday is 4 business days
Any day to the same day in a different week is an even number of weeks and therefore an even mutiple of 5, e.g. Monday 2 Feb to Monday 9 Feb and Sunday 1 Feb to Sunday 8 Feb are 5 business days
Friday 6 Feb to Sunday 7 Feb is zero business days
Friday 6 Feb to Monday 9 Feb is one business day
Sunday 8 Feb to: Sunday 15 Feb, Sat 14 Feb and Fri 13 Feb are all 5 business days
Here's the code:
// Expects start date to be before end date
// start and end are Date objects
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
// Set time to midday to avoid dalight saving and browser quirks
s.setHours(12,0,0,0);
e.setHours(12,0,0,0);
// Get the difference in whole days
var totalDays = Math.round((e - s) / 8.64e7);
// Get the difference in whole weeks
var wholeWeeks = totalDays / 7 | 0;
// Estimate business days as number of whole weeks * 5
var days = wholeWeeks * 5;
// If not even number of weeks, calc remaining weekend days
if (totalDays % 7) {
s.setDate(s.getDate() + wholeWeeks * 7);
while (s < e) {
s.setDate(s.getDate() + 1);
// If day isn't a Sunday or Saturday, add to business days
if (s.getDay() != 0 && s.getDay() != 6) {
++days;
}
}
}
return days;
}
I don't know how it compares to jfriend00's answer or the code you referenced, if you want the period to be inclusive, just add one if the start or end date are a business day.
Here's a simple function to calculate the number of business days between two date objects. As designed, it does not count the start day, but does count the end day so if you give it a date on a Tuesday of one week and a Tuesday of the next week, it will return 5 business days. This does not account for holidays, but does work properly across daylight savings changes.
function calcBusinessDays(start, end) {
// This makes no effort to account for holidays
// Counts end day, does not count start day
// make copies we can normalize without changing passed in objects
var start = new Date(start);
var end = new Date(end);
// initial total
var totalBusinessDays = 0;
// normalize both start and end to beginning of the day
start.setHours(0,0,0,0);
end.setHours(0,0,0,0);
var current = new Date(start);
current.setDate(current.getDate() + 1);
var day;
// loop through each day, checking
while (current <= end) {
day = current.getDay();
if (day >= 1 && day <= 5) {
++totalBusinessDays;
}
current.setDate(current.getDate() + 1);
}
return totalBusinessDays;
}
And, the jQuery + jQueryUI code for a demo:
// make both input fields into date pickers
$("#startDate, #endDate").datepicker();
// process click to calculate the difference between the two days
$("#calc").click(function(e) {
var diff = calcBusinessDays(
$("#startDate").datepicker("getDate"),
$("#endDate").datepicker("getDate")
);
$("#diff").html(diff);
});
And, here's a simple demo built with the date picker in jQueryUI: http://jsfiddle.net/jfriend00/z1txs10d/
const firstDate = new Date("December 30, 2020");
const secondDate = new Date("January 4, 2021");
const daysWithOutWeekEnd = [];
for (var currentDate = new Date(firstDate); currentDate <= secondDate; currentDate.setDate(currentDate.getDate() + 1)) {
// console.log(currentDate);
if (currentDate.getDay() != 0 && currentDate.getDay() != 6) {
daysWithOutWeekEnd.push(new Date(currentDate));
}
}
console.log(daysWithOutWeekEnd, daysWithOutWeekEnd.length);
#RobG has given an excellent algorithm to separate business days from weekends.
I think the only problem is if the starting days is a weekend, Saturday or Sunday, then the no of working days/weekends will one less.
Corrected code is below.
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(start);
var e = new Date(end);
var addOneMoreDay = 0;
if( s.getDay() == 0 || s.getDay() == 6 ) {
addOneMoreDay = 1;
}
// Set time to midday to avoid dalight saving and browser quirks
s.setHours(12,0,0,0);
e.setHours(12,0,0,0);
// Get the difference in whole days
var totalDays = Math.round((e - s) / 8.64e7);
// Get the difference in whole weeks
var wholeWeeks = totalDays / 7 | 0;
// Estimate business days as number of whole weeks * 5
var days = wholeWeeks * 5;
// If not even number of weeks, calc remaining weekend days
if (totalDays % 7) {
s.setDate(s.getDate() + wholeWeeks * 7);
while (s < e) {
s.setDate(s.getDate() + 1);
// If day isn't a Sunday or Saturday, add to business days
if (s.getDay() != 0 && s.getDay() != 6) {
++days;
}
//s.setDate(s.getDate() + 1);
}
}
var weekEndDays = totalDays - days + addOneMoreDay;
return weekEndDays;
}
JSFiddle link is https://jsfiddle.net/ykxj4k09/2/
First Get the Number of Days in a month
totalDays(month, year) {
return new Date(year, month, 0).getDate();
}
Then Get No Of Working Days In A Month By removing Saturday and Sunday
totalWorkdays() {
var d = new Date(); // to know present date
var m = d.getMonth() + 1; // to know present month
var y = d.getFullYear(); // to knoow present year
var td = this.totalDays(m, y);// to get no of days in a month
for (var i = 1; i <= td; i++) {
var s = new Date(y, m - 1, i);
if (s.getDay() != 0 && s.getDay() != 6) {
this.workDays.push(s.getDate());// working days
}else {
this.totalWeekDays.push(s.getDate());//week days
}
}
this.totalWorkingDays = this.workDays.length;
}
I thought the above code snippets others shared are lengthy.
I am sharing a concise snippet that gives date after considering the total number of days specified. we can also customize dates other than Saturdays and Sundays.
function getBusinessDays(dateObj, days) {
for (var i = 0; i < days; i++) {
if (days > 0) {
switch (dateObj.getDay()) {
// 6 being Saturday and 0 being Sunday.
case 6, 0:
dateObj.setDate(dateObj.getDate() + 2)
break;
//5 = Friday.
case 5:
dateObj.setDate(dateObj.getDate() + 3)
break;
//handle Monday, Tuesday, Wednesday and Thursday!
default:
dateObj.setDate(dateObj.getDate() + 1)
//console.log(dateObj)
break;
}
}
}
return dateObj;
}
console.log(getBusinessDays(new Date(), 11))
//Mon Dec 20 2021 18:56:01 GMT+0530 (India Standard Time)

Javascript older than 18 on leap years

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;

Categories