I need to calculate if someone is over 18 from their date of birth using JQuery.
var curr = new Date();
curr.setFullYear(curr.getFullYear() - 18);
var dob =
keep in mind that all above answers work only for date using separator '/'. if you are using other that this then you have to replace that separator first.
var startDate = $('#start_date').val().replace('-','/');
var endDate = $('#end_date').val().replace('-','/');
if(startDate > endDate){
// do stuff here...
}
happy coding :D
You might find the open source Datejs library to be helpful. Specifically the the addYears function.
var dob = Date.parse($(this).text());
if (dob.addYears(18) < Date.today())
{
$(this).text("Under 18");
}
else
{
$(this).text(" Over 18");
}
In a more terse fashion:
$(this).text(
Date.parse($(this).text()).addYears(18) < Date.today() ?
"Under 18" :
" Over 18"
)
You could use the Date object. This will return the milliseconds between the two dates. There are 31556952000 milliseconds in a year.
function dateDiff(var now, var dob)
{
return now.getTime() - dob.getTime();
}
Date.prototype.age=function(at){
var value = new Date(this.getTime());
var age = at.getFullYear() - value.getFullYear();
value = value.setFullYear(at.getFullYear());
if (at < value) --age;
return age;
};
var dob = new Date(Date.parse($(this).text()));
if(dob.age(new Date()) < 18)
{
$(this).text("Under 18");
}
else
{
$(this).text(" Over 18");
}
You can remove the separate variable for DOB and collapse the if statement. The below code comes in at 165 characters:
var check = new Date();
check.setFullYear(check.getFullYear() - 18);
$(this).text((new Date("3/6/2009").getTime() - check.getTime() < 0)?"Under 18":"Over 18");
This will still keep the logic needed to deal with leap-years.
My solution.
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
----------------------------------
}