Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
Tobias4857yYes.
var ageInMilliseconds = (new Date).getTime() - (new Date(birthYear, birthMonth, birthDay)
var age = Math.floor(ageInMilliseconds / 1000 / 3600 / 24 / 365) -
Tobias4857yExplaination:
You create two Date objects. One representing the current time, and one representing your date of birth (with time set to midnight).
.getTime() gives you the number of milliseconds since 1 Jan 1970. Taking the difference between the two gives you the no. of milliseconds you have lived.
Divide the number of milliseconds by 1000 gets you seconds, divide by 3600 gives you hours, divide by 24 gives you days, divide by 365 gives you years. And you must take the floor because you get something like 20.5532... otherwise. -
olback109797y@Tobias Thanks, But wouldn't it technically be 365.25 instead of 365 since every 4 years is 366 days?
-
olback109797y@Tobias It works great but you have to divide by 365.25 to get it right, just tested it.
-
For a first attempt, if it works you can rightly consider it a good effort. I'd have some comments about syntax, but I'm quite picky about such things.
Use just one var block;
Only declare "age" once, not in each branch of your "if";
Don't use "new Date()" each time - store it once then ref the stored version.
Related Rants
I know that this isn't the place to ask questions like this. Anyway, is there a easier way to do this? This code updates my age on my birthday. Also, first attempt to make anything in JS :)
undefined
js
devrant is not so