在 JavaScript 中减去两个日期时,它会给出一个十进制数,但这怎么可能呢?
我正在观看一个视频,其中两个日期之间的差异返回 10,但当我尝试时,它给我一个十进制数,但这是为什么呢?我可以将其包装在 Math.floor() 中,但如果有人解释我,我将不胜感激。 这是代码
const calcDaysPassed = (date1, date2) =>
Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);
const days1 = calcDaysPassed(
new Date(2037, 3, 4),
new Date(2037, 3, 14)
);
console.log(days1);
I'm watching a video where the diff between two dates returns 10 but when I try it gives me a decimal number but why is that? I could wrap it in Math.floor() but I'd appreciate if anyone explain me.
Here is the code
const calcDaysPassed = (date1, date2) =>
Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);
const days1 = calcDaysPassed(
new Date(2037, 3, 4),
new Date(2037, 3, 14)
);
console.log(days1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
日期对象表示时间上的单个瞬间,并且只是相对于 UTC 1970 年 1 月 1 日的偏移量的时间值。
减法运算符强制 Date 对象进行编号,就像通过
date.valueOf()
相当于date.getTime()
,因此当您从一个日期中减去另一个日期时,您会得到它们时间值的差异,例如:因此在您的代码中:
返回差异毫秒:
即 10 个标准天。
请注意,传递给上面 Date 构造函数的值被解释为本地值,因此如果日期范围内存在夏令时转换,则差异可能或多或少取决于夏令时转换的量(通常为 1 小时,但在某些地方为 30分钟)。
有很多类似的问题:
Date objects represent a single instant in time and are just a time value that is an offset from 1 Jan 1970 UTC.
The subtraction operator coerces the Date objects to number as if by
date.valueOf()
which is equivalent todate.getTime()
, so when you subtract one date from another you get the difference in their time values such that:So in your code:
returns the difference in milliseconds:
which is 10 standard days.
Note that the values passed to the Date constructor above are interpreted as local so if there is a daylight saving changeover in the date range the difference might be more or less by the amount of the daylight saving shift (typically 1 hour but in some places 30 minutes).
There are lots of similar questions:
“
Date
对象包含一个Number
,表示自 UTC 1970 年 1 月 1 日以来的毫秒数。” MDNdate2 - date1
返回以下差异毫秒。 MDN:Math.abs(date2 - date1) / (1000 * 60 * 60 * 24)
将毫秒转换为天。"
Date
objects contain aNumber
that represents milliseconds since 1 January 1970 UTC." MDNdate2 - date1
returns the difference in milliseconds. The conversion is described in MDN:Math.abs(date2 - date1) / (1000 * 60 * 60 * 24)
converts the milliseconds to days.