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

How do I Calculate Date Differences in JavaScript?

Mary-Kate Olsen
Release: 2024-11-02 11:13:31
Original
878 people have browsed it

How do I Calculate Date Differences in JavaScript?

Date Difference Calculations in JavaScript

Determining the difference between two dates is a common task in JavaScript. By leveraging the Date object and its millisecond value, this difference can be calculated.

<code class="javascript">var a = new Date(); // Current date
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

To obtain the number of seconds, divide the milliseconds by 1000 and then convert to an integer:

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

For longer time units, continue dividing by appropriate factors and converting to integers:

<code class="javascript">var minutes = parseInt(seconds / 60);
var hours = parseInt(minutes / 60);</code>
Copy after login

Alternatively, create a function to calculate the maximum whole amount of a time unit and the remainder:

<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

Example:

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

Note that when providing input parameters for the Date object, only necessary values need to be specified:

<code class="javascript">new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);</code>
Copy after login

The above is the detailed content of How do I 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!