Home >Web Front-end >JS Tutorial >How Can I Calculate the Time Difference Between Two Dates in JavaScript?

How Can I Calculate the Time Difference Between Two Dates in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-04 22:57:11289browse

How Can I Calculate the Time Difference Between Two Dates in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn