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