How to get the difference between two dates in seconds with TypeScript

2 Answers

0 votes
function getSecondsBetween2Dates(startDate : any, endDate : any): number {
  	const millisecondsInSecond = 1000;

  	return Math.round(Math.abs(endDate - startDate) / millisecondsInSecond);
}

console.log(getSecondsBetween2Dates(new Date(2022, 4, 8, 9, 53, 0), 
                                    new Date(2022, 4, 8, 9, 54, 37)));

  
  
  
/*
run:
  
97
  
*/

 



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

// --- Complete Program Demonstration ---
function main(): void {
    // Define two Date instances with explicit typing (best practice: use ISO 8601 strings)
    const startDate: Date = new Date('2026-10-27T12:00:00Z');
    const endDate: Date = new Date('2026-10-27T12:05:30Z');

    // Call the function to calculate the seconds between the two dates
    const totalSeconds: number = 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 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
...