PDA

View Full Version : JS Code Snippet: get Age from birthdate



tof
8 Jan 2008, 9:04 AM
Since exemples I found on the web were bloated (some 100 lines of code, or so), here is my code snippet to compute an age from a birth date :


Ext.override(Date, {
getAge : function(compareTo) {
compareTo = compareTo || new Date();
compareTo.clearTime();
var age = compareTo.getFullYear() - this.getFullYear();
var d2 = new Date(compareTo.getFullYear(), this.getMonth(), this.getDate());
return (d2 > compareTo ? age - 1 : age);
}
});

You can test it with :

new Date(1966,00,09).getAge()
(Remind that the second argument, "month", starts at zero for january).