如何获得 JavaScript 中两个日期之间的差异? [英] How do I get the difference between two Dates in JavaScript?
问题描述
我正在创建一个应用程序,可让您定义具有时间范围的事件.我想在用户选择或更改开始日期时自动填写结束日期.但是,我无法弄清楚如何获得两次之间的差异,然后如何使用该差异创建新的结束日期.
I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
推荐答案
在 JavaScript 中,可以通过调用 getTime()
方法将日期转换为自 epoc 以来的毫秒数或 仅在数字表达式中使用日期.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime()
method or just using the date in a numeric expression.
所以要得到差异,只需减去两个日期.
So to get the difference, just subtract the two dates.
要根据差异创建新日期,只需在构造函数中传递毫秒数即可.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);
这应该可行
EDIT:修正了@bdukes 指出的错误
EDIT: Fixed bug pointed by @bdukes
编辑:
为了解释行为,oldBegin
、oldEnd
和 newBegin
是 Date
实例.调用运算符 +
和 -
将触发 Javascript 自动转换,并会自动调用这些对象的 valueOf()
原型方法.碰巧 valueOf()
方法在 Date
对象中实现为对 getTime()
的调用.
For an explanation of the behavior, oldBegin
, oldEnd
, and newBegin
are Date
instances. Calling operators +
and -
will trigger Javascript auto casting and will automatically call the valueOf()
prototype method of those objects. It happens that the valueOf()
method is implemented in the Date
object as a call to getTime()
.
所以基本上:date.getTime() === date.valueOf() === (0 + date) === (+date)
这篇关于如何获得 JavaScript 中两个日期之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!