9
olback
7y

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 :)

Comments
  • 5
    Yes.

    var ageInMilliseconds = (new Date).getTime() - (new Date(birthYear, birthMonth, birthDay)

    var age = Math.floor(ageInMilliseconds / 1000 / 3600 / 24 / 365)
  • 2
    Explaination:

    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.
  • 2
    @Tobias Thanks, But wouldn't it technically be 365.25 instead of 365 since every 4 years is 366 days?
  • 0
    ++ for your attempt.
  • 0
    @Tobias It works great but you have to divide by 365.25 to get it right, just tested it.
  • 2
    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.
  • 0
    Which editor are you using? Which theme, too.
    It looks neat.
  • 0
    @hacker VS Code with One Dark Pro i think.
Add Comment