P粉5742689892023-08-21 15:03:33
try it.
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; }
I believe the only part of your code that looks rough is the substr
part.
Fiddle:http://jsfiddle.net/codeandcloud/n33RJ/
P粉4781887862023-08-21 11:57:16
I would choose readability:
function _calculateAge(birthday) { // birthday is a date var ageDifMs = Date.now() - birthday.getTime(); var ageDate = new Date(ageDifMs); // miliseconds from epoch return Math.abs(ageDate.getUTCFullYear() - 1970); }
Disclaimer: This method also has accuracy issues, so it cannot be completely trusted. Errors may occur in certain years, certain hours, or daylight saving time (depending on time zone).
If accuracy is very important, I recommend using a library to handle this. Also, @Naveens post
is probably the most accurate since it is not time dependent.