gpt4 book ai didi

javascript - 试图通过减去两个不同的日期来计算天数

转载 作者:行者123 更新时间:2023-11-30 08:20:09 25 4
gpt4 key购买 nike

我想弄清楚如何减去两个不同的日期以获得余数。根据我的 Google 搜索,这似乎应该非常简单,但我的代码没有按预期工作。

const options = { year: 'numeric', month: 'numeric', day: 'numeric' };
let today = new Date();
today = today.toLocaleDateString('en-US', options); // '2/20/2019'
dueDate = new Date(dueDate[0]);
dueDate = dueDate.toLocaleDateString('en-US', options); // '12/15/2019'
daysLeft = today.setDate(today.setDate() - dueDate); // Being declared as a let outside the scope block

我收到的错误消息是:Uncaught (in promise) TypeError: today.setDate is not a function

enter image description here

更新:

可能重复的答案几乎帮助了我,但它没有考虑年份,所以 2/20/2019 - 2/1/2001 输出 19,这是不正确的。

最佳答案

您可以直接使用数学。

let today = new Date();
let dueDate = new Date('12/15/2019');
let difference = Math.abs(Math.round((today.getTime()-dueDate.getTime())/1000/24/60/60));
console.log(difference);

通过这种方式,我们得到以毫秒为单位的差异,除以 1000 得到秒,除以 60 得到分钟,再除以 60 得到小时,最后除以 24 得到天差。

关于javascript - 试图通过减去两个不同的日期来计算天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787148/

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