JS Date()返回NaN,即使使用toString()

时间:2016-06-24 16:25:24

标签: javascript jquery

我有这段代码来计算用户的年龄:

// Get today's date
var today = new Date();
var dd = today . getDate();
var mm = today . getMonth() + 1;
var yyyy = today . getFullYear();

if( dd < 10 ) {

    dd = '0' + dd;

} 

if( mm < 10 ) {

    mm = '0' + mm;

} 

/*
* Calculate the age in days
*/
var minimum_age_in_days = 6574;

var date_of_birth_formatted = new Date( year + '/' + month + '/' + day );
today = yyyy + '/' + mm + '/' + dd;

var difference = today - date_of_birth_formatted;

var difference_in_days = difference / 100 / 60 / 60 / 24 / 10;

console . log( difference ) . toString();
console . log( difference_in_days ) . toString();

if( difference_in_days < minimum_age_in_days ) {

    $( "#formModal" ) . show();
    $( "#overlay" ) . hide();
    alert( "You're not 18 years old" );

}

else {

    // Hide first modal
    $( "#formModal" ) . hide();

    // Show second modal
    $( "#overlay" ) . show();

}

两个console.log()返回NaN,而我已经尝试将它们转换为字符串,因此我可以执行if()语句。但是,由于这些变量(difference&amp; difference_in_days)的值为NaN,因此代码会中断。如何转换这些值,因此代码不会中断?

2 个答案:

答案 0 :(得分:1)

麻烦来自这两条线:

var date_of_birth_formatted = new Date( year + '/' + month + '/' + day );
today = yyyy + '/' + mm + '/' + dd;

// examine them:
typeof date_of_birth_formatted  // returns "object"
typeof today // returns "string"

您将通过从Date对象中减去字符串来获取NaN。而不是为了获得今天的日期所做的额外工作,请尝试直接使用新的日期。然后您的代码可以简化为:

var date_of_birth_formatted = new Date( year + '/' + month + '/' + day );

var difference = new Date() - date_of_birth_formatted;

var difference_in_days = difference / 100 / 60 / 60 / 24 / 10;

console.log( difference ).toString();
console.log( difference_in_days ).toString();

答案 1 :(得分:1)

问题在第25行: registerComponentCallbacks(new CustomComponentCallback()); registerActivityLifecycleCallbacks(new CustomLifeCycleCallbacks()); 您可以通过删除此行来解决您的问题。

原因:上面一行(25)将您的今天对象更改为字符串类型。 today = yyyy + '/' + mm + '/' + dd;typeof today。虽然stringtypeof date_of_birth_formatted。从字符串中减去对象正在返回object