且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获得 JavaScript 中两个日期之间的差异?

更新时间:2023-01-30 08:52:40

在 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

编辑:

为了解释行为,oldBeginoldEndnewBeginDate 实例.调用运算符 +- 将触发 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)