2 回答

TA貢獻1829條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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>
添加回答
舉報