Calculating the Time Difference Between Two Dates in JavaScript
In JavaScript, you can leverage the getTime() method or simply use a date in a numeric expression to convert it to milliseconds since the Unix epoch. To obtain the time difference, simply subtract the two dates.
To create a new date based on the difference, pass the number of milliseconds to the constructor. Here's an example:
var oldBegin = ... var oldEnd = ... var newBegin = ... var newEnd = new Date(newBegin + oldEnd - oldBegin);
This operation should yield the desired result.
Explanation:
Date instances (oldBegin, oldEnd, and newBegin) trigger JavaScript auto casting when used with operators like and -. This triggers a call to the valueOf() method, which for Date objects returns the number of milliseconds since the epoch.
Therefore:
date.getTime() === date.valueOf() === (0 + date) === (+date)
The above is the detailed content of How Can I Calculate the Time Difference Between Two Dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!