0

Script for generating an age?

Is there a simple script for generating an age based on the current year- that could be say, put on a page where a biography lists someones Name, Age, Experience, and Hobbies. Ex: Joe was born in LA. He is 28 years old, loves hockey and works out a lot. Now we know Joe is 28 now, and it's 2016. So it's safe to say that this time next year he will be 29. Is there a short way to script the document to write Joe's age as 29 instead of 28 starting on June 1st, 2017? I'm looking for a way to do this on bio pages for websites so that no one needs to remember to update them if they go untouched for a long time.

19th Oct 2016, 5:05 AM
Aaron Tucci
1 Resposta
+ 5
Javascript has a builtin `Date` that seems perfect for the job. Store Joe's birthdate in a variable and then calculate the difference. var birthdate = new Date(1988, 5, 1), // Months go from 0-11 now = new Date(), difference = now - birthdate; `difference` now contains Joe's age, in milliseconds! There are many ways to convert this but an easy one is using `Date`, too. var temp = new Date(difference), tempyear = temp.getFullYear(); So we plug the age in milliseconds into the `Date` constructor and use the `getFullYear` method to convert that to years. The way Javascript sets things up, `new Date(0)` would be January 1st, 1970 (look up unix time), so we need to subtract 1970 from `tempyear`. var age = tempyear - 1970; And that's it! You can then print the age onto the screen. Note that on rare occasions, things may be a day off when leap years are involved, I didn't really account for that. For doing serious work I recommend http://momentjs.com/ :)
19th Oct 2016, 7:10 AM
Schindlabua
Schindlabua - avatar