使用JQuery的出生日期的年龄 [英] Age from Date of Birth using JQuery

查看:104
本文介绍了使用JQuery的出生日期的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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");
}

必须使用一些更简单的函数来比较日期,而不是使用setFullYear和getFullYear方法。

There must be some easier functions to use to compare dates rather than using the setFullYear and getFullYear methods.

注意:我想要找到一个新方法的实际原因是代码的长度。我必须将此代码适用于限制为250个字符的数据库字段。

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.

推荐答案

您可能会发现开源的 Datejs 库是有帮助的。具体来说, addYears function。

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");
}

更简洁的方式:

$(this).text(
    Date.parse($(this).text()).addYears(18) < Date.today() ?
    "Under 18" :
    " Over 18"
)

这篇关于使用JQuery的出生日期的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆