Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,700 questions

57,013 answers

573 users

How to get the number of seconds between two dates in 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 4 hours ago 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 3 hours ago by avibootz
...