如何根据出生日期来计算两个日期之间的差异

时间:2020-09-10 13:01:52

标签: javascript algorithm date

我的代码:

        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)));
        }

示例1

如果我出生于

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

我将930426作为值传递给测试函数,并且结果将是27,这是正确的

但是在示例2 中:

如果我出生于:

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

我将通过930914作为测试函数的值,结果将为27,但这是不正确的,因为我的生日还没到,我仍然26岁。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

由于26.9仍被视为26的年龄,因此您应该改用.floor

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