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

How to Calculate Date Differences in JavaScript?

Mary-Kate Olsen
Release: 2024-11-02 07:43:29
Original
907 people have browsed it

How to Calculate Date Differences in JavaScript?

Determining Date Differences in JavaScript

Finding the difference between two dates in JavaScript involves utilizing the Date object and its milliseconds value. For instance, let's consider the following 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

This calculation provides the number of milliseconds between the current date (a) and the specified date (b), representing the elapsed time. To obtain the difference in seconds, simply divide the milliseconds by 1000 and round it to an integer:

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

If you require the difference in larger time units, such as minutes, hours, or even days, you can employ the get_whole_values function demonstrated below:

<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;
};</code>
Copy after login

This function takes a base value (e.g., milliseconds) and an array of time fractions (e.g., seconds per minute, minutes per hour) as parameters. It then calculates the whole amount of each time unit and the remainder in the original unit.

For instance, consider the following example:

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

This result indicates that 72000 milliseconds translates to 0 milliseconds, 12 seconds, and 1 minute.

The above is the detailed content of How to Calculate Date Differences 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!