如何检查年龄是否在特定年份之间?

时间:2018-12-11 21:08:02

标签: javascript date

我想检查输入的年龄是否小于3个月,是否介于3个月至3年之间或大于7岁。所以这是我的代码:

var today = new Date();
var age = (today - new Date('11.11.2010')) / (24 * 60 * 60 * 1000);
var threeMonth = new Date();
var threeYears = new Date();
var sevenYears = new Date();
var threeMonth = new Date(threeMonth.getFullYear(), threeMonth.getMonth() - 3, threeMonth.getDate());
var threeYears = new Date(threeYears.getFullYear() - 3, threeYears.getMonth(), threeYears.getDate());
var sevenYears = new Date(sevenYears.getFullYear() - 7, sevenYears.getMonth(), sevenYears.getDate());
var diff1 = (today - threeMonth) / (24 * 60 * 60 * 1000);         
var diff2 = (today - threeYears) / (24 * 60 * 60 * 1000);         
var diff3 = (today - sevenYears) / (24 * 60 * 60 * 1000);         
if (age < diff1) {                      
console.log('less than 3 month')
} else if (age > diff2 && age < diff3) { 
console.log('greater than 3 month, less than seven years')
} else if (age > diff3) {               
console.log('greater than seven years')
}

我最近刚熟悉编程,并且对我是否错过了某些东西的疑问困扰着我,此外,代码庞大且难以阅读。 还有其他解决此问题的正确方法吗?

2 个答案:

答案 0 :(得分:0)

Moment非常适合简化日期计算。您的逻辑也可以简化:

const old = moment('2010-11-11');  // use ISO format
const ageInMonths = moment().diff(old, 'months');

if (ageInMonths < 3) {
  console.log('less than 3 month');
} else if (ageInMonths < 7 * 12) {
  console.log('greater than 3 month, less than seven years');
} else {
  console.log('greater than seven years');
}

答案 1 :(得分:0)

请参见下面

    function  inMonths() {

    d1=new Date('1/1/2001');
    d2=new Date('1/1/2002');

    var d1Y = d1.getFullYear();
    var d2Y = d2.getFullYear();
    var d1M = d1.getMonth();
    var d2M = d2.getMonth();

    var diff=(d2M+12*d2Y)-(d1M+12*d1Y);

    if (diff <3)
      alert("Less then three months");
    else if (diff > 3 && diff< 84)
       alert("More then three but less then seven years");  
    else if (diff>84)
       alert("More then seven years");
}