Home  >  Article  >  Web Front-end  >  How do I Calculate Date Differences in JavaScript?

How do I Calculate Date Differences in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 11:13:31879browse

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>

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>

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>

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;
}

Example:

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

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>

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!

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