gpt4 book ai didi

javascript - "a.getFullYear is not a function"尝试获取日期差异时

转载 作者:行者123 更新时间:2023-12-02 15:28:27 26 4
gpt4 key购买 nike

我正在尝试使用 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);

最佳答案

您需要将 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);
}

关于javascript - "a.getFullYear is not a function"尝试获取日期差异时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com