How to get the difference between two dates in seconds with Node.js

2 Answers

0 votes
function getSecondsBetween2Dates(startDate, endDate) {
    const millisecondsInSecond = 1000;
 
    return Math.round(Math.abs(endDate - startDate) / millisecondsInSecond);
}
 
console.log(getSecondsBetween2Dates(new Date(2022, 4, 08, 10, 04, 0), 
                                    new Date(2022, 4, 08, 10, 05, 39)));
 
   
   
   
   
/*
run:
   
99
   
*/

 



answered Apr 8, 2022 by avibootz
edited Oct 27 by avibootz
0 votes
/**
 * Calculates the total number of seconds between two Date objects.
 * 
 * @param {Date} startDate - The starting date and time.
 * @param {Date} endDate - The ending date and time.
 * @returns {number} The total number of seconds, including fractional seconds.
 */
function getSecondsBetween2Dates(startDate, endDate) {
    // Retrieve timestamps in milliseconds using .getTime() and calculate the difference
    const differenceInMilliseconds = endDate.getTime() - startDate.getTime();
    
    // Convert milliseconds to seconds
    return differenceInMilliseconds / 1000;
}

// --- Complete Node.js Program Demonstration ---
function main() {
    // Define two Date instances using ISO 8601 strings (best practice for server-side consistency)
    const startDate = new Date('2026-10-27T12:00:00Z');
    const endDate = new Date('2026-10-27T12:05:30Z');

    // Call the function to calculate the seconds between the two dates
    const totalSeconds = getSecondsBetween2Dates(startDate, endDate);

    // Output the results to the console
    console.log(`Start Date: ${startDate.toISOString()}`);
    console.log(`End Date: ${endDate.toISOString()}`);
    console.log(`Total Seconds Between: ${totalSeconds}`);
}

// Execute the Node.js program
main();
   
   
   
/*
run:
   
Start Date: 2026-10-27T12:00:00.000Z
End Date: 2026-10-27T12:05:30.000Z
Total Seconds Between: 330
   
*/

 



answered Oct 27 by avibootz
...