这个项目的想法很简单:一个能从用户那里检索输入的计算器,希望是以日期-时间的格式,尽管我不知道该如何做,所以现在我正在检索整数,并从它们中构造一个日期,它减去今天的日期,给出在输入日期之前剩下的天数。是的,这可能很简单,但我不知道自己做错了什么,因为现在我在HTML中得到了一个值。因此,再次明确的是,用户输入日期,JS将计算出该日期之前的天数。请尽可能少地帮助我,任何小的帮助对我都很重要。
这是我到目前为止掌握的代码:
var today = new Date();
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")
today = mm + '/' + dd + '/' + yyyy;
const oneDay = 24 * 60 * 60 * 1000;
var oneDate = new Date(y, yy, yyy);
var diffDays = Math.round(Math.abs((oneDate - today) / oneDay));
document.write(diffDays)发布于 2020-07-25 11:00:13
你们真的很亲密。你无缘无故地给今天重新分配一个字符串,把它当作一个日期。但既然你想整日,你就得把时间调到零。
另外,从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)
发布于 2020-07-25 10:53:11
您可以使用代杰斯库轻松地做到这一点。它只有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>
https://stackoverflow.com/questions/63087106
复制相似问题