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:
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.
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:
var seconds = parseInt((b - a) / 1000);
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:
function get_whole_values(base_value, time_fractions) {
time_data = [base_value];
for (i = 0; i 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:
console.log(get_whole_values(72000, [1000, 60])); // [0, 12, 1]
This result indicates that 72000 milliseconds translates to 0 milliseconds, 12 seconds, and 1 minute.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3