0

My code:

        function test(val) {
            year = parseInt(val.slice(0,2)); // get year
            month = parseInt(val.slice(2,4)); // get month
            date = val.slice(4,6); // get date

            if (month > 40) { // For people born after 2000, 40 is added to the month. (it is specific for my case)
                year += 2000;
                month -= 40;
            } else {
                year += 1900;
            }

            date = new Date(year, month-1, date, 0, 0);
            date_now = new Date();

            var diff =(date_now.getTime() - date.getTime()) / 1000;
            diff /= (60 * 60 * 24);
            console.log(Math.abs(Math.round(diff/365.25)));
        }

Example 1:

If I was born in

1993-year;
04-month(april); 
26-date

I will pass 930426 as value to test function and the result would be 27 which is correct

But in Example 2:

If I was born in:

1993-year;
09-month(september); 
14-date;

I will pass 930914 as value to test function and result would be 27, but it's not correct because my birthday is still not come and i'm still 26 years old.

How can I fix this ?

Sahin Urkin
  • 289
  • 1
  • 8
  • 1
    Does this answer your question? [How can I calculate the number of years between two dates?](https://stackoverflow.com/questions/8152426/how-can-i-calculate-the-number-of-years-between-two-dates) – Jpsh Sep 10 '20 at 13:17
  • I do not want to use moment.js – Sahin Urkin Sep 10 '20 at 14:41

1 Answers1

1

Because 26.9 is still regarded as age of 26, so you should use .floor instead

function test(val) {
  year = +val.slice(0, 2) // get year
  month = val.slice(2, 4) // get month
  date = val.slice(4, 6) // get date

  date = new Date(year, month - 1, date, 0, 0)
  date_now = new Date()

  var diff = (date_now.getTime() - date.getTime()) / 1000
  diff /= 60 * 60 * 24
  console.log(diff / 365.25)
  console.log("Age", Math.floor(diff / 365.25))
}

test("930426")
test("930914")
hgb123
  • 13,869
  • 3
  • 20
  • 38
  • I thought that it works fine, but if you check with `test("940911")` and `test("940909")` It returns 26 for both, which is not correct. – Sahin Urkin Sep 10 '20 at 13:38