【问题标题】:How to take the differences between two dates, depending on the date of birth [duplicate]如何取两个日期之间的差异,具体取决于出生日期[重复]
【发布时间】:2020-09-10 21:22:10
【问题描述】:

我的代码:

        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 岁。

我该如何解决这个问题?

【问题讨论】:

标签: javascript algorithm date


【解决方案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")

【讨论】:

  • 我认为它工作正常,但如果你检查 test("940911")test("940909") 两者都返回 26,这是不正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多