OOP JS (calculate age)
JavaScript
function Student(fullName, birthday, major, email, studentId, city, state, age)
{
this.fullName = fullName;
this.birthday = birthday;
this.major = major;
this.studentId = studentId;
this.city = city;
this.state = state;
this.age = age;
this.getAddress = function()
{
return this.city + " " + this.state;
}
}
Student.prototype.age = function() {
var toDate = new Date();
var fromDate = new Date(this.birthday), age = [];
ydiff = y[0] - y[1],
m = [toDate.getMonth(), fromDate.getMonth()],
mdiff = m[0] - m[1],
d = [toDate.getDate(), fromDate.getDate()],
ddiff = d[0] - d[1];
if(mdiff < 0 || (mdiff === 0 && ddiff < 0))
{
--ydiff;
}
if(mdiff < 0)
{
mdiff += 12;
}
if(ddiff < 0)
{
fromDate.setMonth(m[1] + 1, 0);
ddiff = fromDate.getDate() - d[1] + d[0];
--mdiff;
}
if(ydiff> 0)
{
age.push(ydiff+ ' year'+(ydiff> 1? 's ':' '));
}
if(mdiff> 0)
{
age.push(mdiff+ ' month'+(mdiff> 1? 's':''));
}
if(ddiff> 0)
{
age.push(ddiff+ ' day'+(ddiff> 1? 's':''));
}
if(age.length>1)
{
age.splice(age.length-1,0,' and ');
}
return age.join('');
}
var Students = [];
var student = new Student("Ly Manh Long", 1996/07/20, "Engineering", "[email protected]", "1431200008", "Thu Dau Mot", "Binh Duong", 1);
Students.push(student);