The rewritten title is: Calculate age based on date of birth in YYYYMMDD format
P粉265724930
2023-08-20 16:03:39
<p>How to calculate age based on date of birth in YYYYMMDD format? Is it possible to use the <code>Date()</code> function? </p>
<p>I'm looking for a better solution than what I'm using now: </p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);</pre>
<p><br /></p>
try it.
I believe the only part of your code that looks rough is the
substr
part.Fiddle:http://jsfiddle.net/codeandcloud/n33RJ/
I would choose readability:
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.