如何在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);

这应该只是工作

编辑:修正由@bdukes指出的错误

EDIT: Fixed bug pointed by @bdukes

编辑

有关行为的解释, oldBegin oldEnd newBegin 日期实例。调用运算符 + - 将触发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)