Javascript is kind of wonky about their dates. Here is a simple function to calculate age based on a given date string.
1 2 3 4 5 6 7 8 9 10 11 |
function calculateAge(birthdate){ var today = new Date(); today = Date.parse(today); var minutes = 1000 * 60; var hours = minutes * 60; var days = hours * 24; var years = days * 365.25; return Math.floor((today-birthdate) / years); } |
Note: This is not perfect and does not work with every possible date string, but it works pretty well with all standard US date formats.
Here is some decent code to setup some simple date masking.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
$('.datemask').on('keydown', function(e){ if (e.key.length == 1 && isNaN(e.key)){ e.preventDefault(); return false; } if (e.key.length == 1){ var v = this.value; if (v.match(/^\d{2}$/) !== null) { if(v > 12) v = 12; this.value = v + '/'; } else if (v.match(/^\d{2}\/\d{2}$/) !== null) { v = v.split('/'); if(v[0]>12) v[0] = 12; if(v[1]>31) v[1] = 31; this.value = v[0] + '/' + v[1] + '/'; }else if (v.match(/^\d{2}\/\d{2}\/\d{4}$/) !== null) { v = v.split('/'); if(v[0]>12) v[0] = 12; if(v[1]>31) v[1] = 31; var year = new Date().getFullYear(); var oldest = year - 150; if(v[2]<oldest) v[2] = oldest; if(v[2]>year) v[2] = parseInt(year)-1; this.value = v[0] + '/' + v[1] + '/' + v[2]; } return this.value; } }); |