本文介绍了如何确定两个日期之间的差异,具体取决于出生日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

        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,这是正确的

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

但是在示例2 中:

如果我出生于:

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

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

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.

我该如何解决?

推荐答案

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

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

这篇关于如何确定两个日期之间的差异,具体取决于出生日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 16:08