在javascript中确定未来的年龄

时间:2014-05-08 18:33:46

标签: javascript jquery ajax

我正在开展一个项目,要求我实施一种方法,确定劳动节后一天的人口年龄;每年9月的第一个星期一。

这种方法将在未来几年使用,因此需要确定当天的年份和劳动节后一天的年龄。

以下是我用来了解学生当前年龄的代码:

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
       age--;
    }
    return age;  //this returns the students current age
}

谢谢!

2 个答案:

答案 0 :(得分:3)

改变了代码。所以它可以处理更多情况。

请参阅此处的小提琴:http://jsfiddle.net/y6kTc/

function getAge(birthday, whatDay) {
    var whatDay = whatDay || new Date(),
        birthday = typeof birthday.getTime === "function" ? birthday : new Date(birthday)

    var age = whatDay.getFullYear() - birthday.getFullYear(),
        m = whatDay.getMonth() - birthday.getMonth();

    if (m < 0 || (m === 0 && whatDay.getDate() < birthday.getDate())) {
       age--
    }

    return age  //this returns the students current age    
}

默认情况下,您可以为生日传递日期字符串或日期对象,并获取当前的生日getAge( new Date("5/29/1988") )getAge("5/29/1988")

真正的魔法发生在whatDay参数上。有了它,您可以设置将来的一天计算getAge("5/29/1988", new Date("9/1/2014"))

为了得到像劳动节这样的日子你可以传递一个自我调用函数来计算那一天:

getAge( "5/29/1988", (function(date) {
    var year = date.getFullYear(),
        day = 1

    date.setMonth(8)
    date.setDate(day) //8 for September, 1 for the first

    while (date.getDay() !== 1) {
        date.setDate(day++)
    }

    return date        
})(new Date()) )

答案 1 :(得分:1)

今天换成劳动节后的第二天:

function firstMonday (month, year)
{
    // allow month to be actual month and not zero based
    var d = new Date(year, month - 1, 1, 0, 0, 0, 0)
    var day = 0

    // check if first of the month is a Sunday, if so set date to the second

    if (d.getDay() == 0) 
    {
        day = 2
        d = d.setDate(day)
        d = new Date(d)
    }

    // check if first of the month is a Monday, if so return the date, otherwise get to the Monday following the first of the month

    else if (d.getDay() != 1) 
    {
        day = 9-(d.getDay())
        d = d.setDate(day)
        d = new Date(d)
    }

    return d;
}

function getFutureAge(dateString) 
{
    var today = new Date();
    var monday = firstMonday(9, today.getFullYear());
    var laborDay = new Date(today.getFullYear(), 9, monday.getDay() + 1, 0, 0, 0);
    var birthDate = new Date(dateString);
    var age = laborDay.getFullYear() - birthDate.getFullYear();
    var m = laborDay.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
       age--;

    return age;  //this returns the students current age
}

console.log(getFutureAge('09/01/1996'));

输出:

18

jsFiddle:http://jsfiddle.net/4syBQ/