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 = Date.parse($(this).text());
if((curr-dob)<0)
{
$(this).text("Under 18");
}
else
{
$(this).text(" Over 18");
}
There must be some easier functions to use to compare dates rather than using the setFullYear and getFullYear methods.
Note: My actual reason for wanting to find a new method is length of the code. I have to fit this code into a database field that is limited to 250 chars. Changing the database is not something that can happen quickly or easily.
You need to parse it into an actual number. dob = new Date(dob); var today = new Date(); var age = Math. floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000)); $('#age'). html(age+' years old');
function calculateAge(date) { const now = new Date(); const diff = Math. abs(now - date ); const age = Math. floor(diff / (1000 * 60 * 60 * 24 * 365)); return age } var picker = new Pikaday({ field: document.
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"
)
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With