2 回答

TA贡献1829条经验 获得超7个赞
你实际上非常接近。您无缘无故地将一个字符串重新分配给今天,只是将其保留为日期。但是因为你想要一整天,你需要将时间归零。
此外,从yy中减去 1,因为它将是日历月份编号,而不是 ECMAScript 月份编号,因此:
var today = new Date();
// zero the time
today.setHours(0,0,0,0);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
var y = prompt("Enter the year")
var yy = prompt("Enter the month")
var yyy = prompt("Enter the day")
// don't do this
//today = mm + '/' + dd + '/' + yyyy;
const oneDay = 24 * 60 * 60 * 1000;
// Subtract 1 from month number
var oneDate = new Date(y, yy - 1, yyy);
var diffDays = Math.round(Math.abs((oneDate - today) / oneDay));
document.write(diffDays)

TA贡献1864条经验 获得超2个赞
您可以使用Dayjs库轻松完成此操作。它只有 2KB,所以它不会使您的页面变大很多,但会让您的生活变得更简单。
这是浏览器的完整工作示例:
dayjs.extend(window.dayjs_plugin_duration)
dayjs.extend(window.dayjs_plugin_relativeTime)
const now = dayjs();
const year = prompt("Enter the year");
const month = prompt("Enter the month");
const day = prompt("Enter the day");
const userDate = dayjs(new Date(year, month - 1, day));
const difference = dayjs.duration(now.diff(userDate)).asDays();
document.write(`${Math.round(difference, 0)} days`);
<script src="https://unpkg.com/dayjs@1.8.30/dayjs.min.js"></script>
<script src="https://unpkg.com/dayjs@1.8.30/plugin/relativeTime.js"></script>
<script src="https://unpkg.com/dayjs@1.8.30/plugin/duration.js"></script>
添加回答
举报