当试图获得日期差异时,“a.getFullYear不是函数”

时间:2015-11-04 01:06:41

标签: javascript date

我正试图通过JS获取日期和今天之间的日期差异。 这是我的代码,但我得到“a.getFullYear不是函数”。

var brbr = '<br><br>';
var duedate="2015-11-06";
document.write(duedate);
document.write(brbr);

// Today's date:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();

if(dd<10) {
    dd='0'+dd
} 

if(mm<10) {
    mm='0'+mm
} 
today = yyyy+'-'+mm+'-'+dd;
document.write(today);
document.write(brbr);

// DIFFERENCE 2 dates:
var _MS_PER_DAY = 1000 * 60 * 60 * 24;


// a and b are javascript Date objects
function dateDiffInDays(a, b) {
    // Discard the time and time-zone information.
    var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

结果:

var days_left = dateDiffInDays(today, duedate);
document.write(days_left);
document.write(brbr);

2 个答案:

答案 0 :(得分:1)

您需要将todayduedate转换为Date()个对象才能使用.getFullYear()

function dateDiffInDays(a, b) {
    var aDate = new Date(a);
    var bDate = new Date(b);

    // Discard the time and time-zone information.
    var utc1 = Date.UTC(aDate.getFullYear(), aDate.getMonth(), aDate.getDate());
    var utc2 = Date.UTC(bDate.getFullYear(), bDate.getMonth(), bDate.getDate());
    return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

答案 1 :(得分:1)

我做的是:

var a = Date.parse("date");
var b = new Date(a);