-1

I think my problem is easy to solve but I just can't get the hang of it. I want a function, which checks if the person is turning 18 in the current year, but the person doesn't have to be already 18 at the moment of checking.

Example: "Mike turns 18 next week". So he's still 17 today, but the function should return true, because he's turning 18 this year. If Mike turns 18 in the next year, the function should return false.

This is what I got so far, but this function only checks if the person is already 18 or not.

dateString = "2000-02-23" // person is 17 but turns 18 next week, so function should return true
otherDateString = "2001-01-13" //person is also 17, but function should return false, because this person just turnt 17 this year and will turn 18 next year

calculateAge(dateString) {
    let birthday = new Date(dateString);
    let ageDifMs = Date.now() - birthday.getTime();
    let ageDate = new Date(ageDifMs); // milliseconds from epoch
    let age = Math.abs(ageDate.getFullYear() - 1970);
    console.log(age);
    if (age>=18)
      return true;
  }

How do I have to change the function to just check if the person is turning 18 this year, no matter if the person is still 17 yet?

BlueCat
  • 673
  • 4
  • 16
  • 27
  • 1
    Just compare the years, the months, and the day-of-month. I mean, how would you do this with paper and pencil? – Pointy Feb 16 '18 at 15:12
  • 1
    If you only care about the year, and it doesn't matter if they're already 18, all you need to check is if `currentYear == yearOfBirth + 18` –  Feb 16 '18 at 15:14

2 Answers2

1

It should be easy enough to do it like this:

dateString = "2000-02-23" // person is 17 but turns 18 next week, so function should return true
otherDateString = "2001-01-13" //person is also 17, but function should return false, because this person just turnt 17 this year and will turn 18 next year

function calculateAge(dateString) {
    let birthday = new Date(dateString);
    let now = new Date();
    return now.getYear() - birthday.getYear() >= 18;
}
Serates
  • 106
  • 4
  • Note that dates in ISO 8601 format will likely be parsed as UTC, so this will produce incorrect results around new year for the period of the local timezone offset. You should avoid using the built-in parser, it's unreliable and can produce unexpected results (like being inconsistent with ISO 8601 in some respects but not others). – RobG Feb 18 '18 at 07:58
0

You don't need to parse the input date string to a Date, in fact it's better if you don't. See Why does Date.parse give incorrect results?

All you need to do is get the year from the date string and subtract it from the current year. If the result is 18, they turn 18 this year:

function eighteenThisYear(s) {
  return new Date().getFullYear() - s.split(/\D/)[0] == 18;
}

['1999-12-31','2000-02-23','2001-02-03'].forEach(function(d) {
  console.log(d + ': ' + eighteenThisYear(d));
});
RobG
  • 142,382
  • 31
  • 172
  • 209