Apparent age mangler
Posted by gregster on 03 Apr 2017 in Activity log
Attestation paper has a field that asks for apparent age in years and months. Using the example '30 years 4 months' as an example, we'll ask editors to enter it thusly 30:4
Here's some javascript that will take 30:4 and turn it in to 364. We'll store that in the database as an integer.
// incoming
var ageFromInput = "30:4"; // this needs to be a string
var ageArr = ageFromInput.split(':');
var ageSubYears = parseInt(ageArr[0]); // this needs to be an integer
var ageSubMonths = parseInt(ageArr[1]); // this needs to be an integer
var ageInMonthsYears = ageSubYears*12;
var ageInMonthsTotal = ageInMonthsYears+ageSubMonths; // should be 364
console.log(ageInMonthsTotal);
When we display the data, we'll reverse things, taking the 364 from the DB and turning it in to the correct display format
// outgoing var ageInMonths = 364; // int value from DB var ageDecimal = ageInMonths/12; // should give us 30.333333333333332 var ageYears = Math.floor(ageDecimal); // should give us 30 // to handle the months display, we need to get the decimal // value (0.333333333333332) with modulus (%), multiply by 12 and round var ageMonthsRemainder = Math.round((ageDecimal % 1)*12); //should give us 4 var ageDisplay = ageYears + ":" + ageDecimalRemainder; // should give us 30:4 console.log(ageDisplay);