Rewriting my answer a bit because I found some issues after reading the comments! Generally your code works, but you WILL have issues with dates after 1999 because a two-digit year after that can begin with a leading zero, which is not allowed in a number. For example in the console running console.log(001234)
will produce 668
since it apparently will try to convert this number into octal!
So, you absolutely must have the "numbers" input as strings of numbers to ensure your data is accurate. This means you must always save these number as strings, and pass them around as strings.
With that covered the other issue is that dates after 1999 will assume a '19' prefix. So a number of '001205'
will assume the year meant by 00
is 1900
and not 2000
. As it was pointed out above in a comment there is a 0.025% chance for a person to be over 100 years old, and that a person this old in this country may not have even been issued a number, this seems like it's safe to assume they were worn in this century.
I think a good way to address this is to compare the two digit input year against the last two digits of the current year. As I write this is is 2023
, so that becomes 23
. Here are some examples
- An input year of
05
is less than 23
so we can prepend 20
so the full year is 2005
.
- An input year of
27
is greater than 23
so we can prepend 19
so the full year is 1927
.
Here is my recommendation that takes all of this into account. I also removed the need for a Date
object. This means we don't need to subtract 1 from the month now either. We can just get the numbers from the string and then parse them into real numbers.
function parseIdNumber(numStr){
//if the last 2 digits of the input year are less than the last 2 of the current year
//assume they were born after the year 2000
var currentYearTwoDigits = parseInt(new Date().getFullYear().toString().substring(2,4), 10);
var inputYear = parseInt(numStr.substring(0, 2), 10);
var bestGuessYear = (inputYear < currentYearTwoDigits ? '20' : '19') + inputYear;
return {
day: parseInt(numStr.substring(4, 6), 10),
month: parseInt(numStr.substring(2, 4), 10),
year: parseInt(bestGuessYear, 10)
}
}
console.log(parseIdNumber('541213'));
console.log(parseIdNumber('841003'));
console.log(parseIdNumber('930214'));
console.log(parseIdNumber('991205'));
console.log(parseIdNumber('000101'));
console.log(parseIdNumber('071205'));
console.log(parseIdNumber('220824'));