Home > Web Front-end > JS Tutorial > body text

How to Calculate the Difference Between Two Dates in JavaScript?

Patricia Arquette
Release: 2024-11-02 08:52:28
Original
975 people have browsed it

How to Calculate the Difference Between Two Dates in JavaScript?

Calculating Differences Between Dates in JavaScript

Finding the difference between two dates is a common task in JavaScript. This difference can be expressed in milliseconds, seconds, minutes, hours, or any other desired time unit.

Using the Date Object

JavaScript provides the Date object to handle dates and times. The Date object has a getTime() method that returns the number of milliseconds since January 1, 1970 midnight. By subtracting the milliseconds of one date from another, we can obtain the difference in milliseconds between them.

Example:

<code class="javascript">var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b - a); // Difference in milliseconds.</code>
Copy after login

Converting Milliseconds to Other Units

To convert milliseconds to other time units, we can divide by the appropriate conversion factor. For example, to get the number of seconds, we divide by 1000:

<code class="javascript">var seconds = parseInt((b - a) / 1000);</code>
Copy after login

Calculating Whole Units and Remainders

If we need to find the whole number of a larger time unit within a smaller one, we can use a function like this:

<code class="javascript">function get_whole_values(base_value, time_fractions) {
    time_data = [base_value];
    for (i = 0; i < time_fractions.length; i++) {
        time_data.push(parseInt(time_data[i] / time_fractions[i]));
        time_data[i] = time_data[i] % time_fractions[i];
    };
    return time_data;
}
Copy after login

This function takes the base value (e.g., milliseconds) and a list of time fractions (e.g., [1000, 60] for seconds and minutes). It returns an array containing the whole number of each unit and the remaining portion.

Example:

<code class="javascript">console.log(get_whole_values(72000, [1000, 60]));
// -> [0, 12, 1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.</code>
Copy after login

The above is the detailed content of How to Calculate the Difference Between Two Dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!