Calculate Number of Days Between Two Dates in TypeScript

While working on a project tracking system using TypeScript, I got a requirement to calculate the duration of tasks in days. Each task had a start date and an end date, and I needed to display how long each task took to complete based on those two dates. To do this, I had to calculate the number of days between two dates.

In the examples below, I’ll explain how to calculate the number of days between two dates in TypeScript using the built-in Date object.

Why TypeScript for Date Calculations?

TypeScript extends JavaScript by adding static types, which helps in catching errors early in the development process. When working with dates, this can be particularly useful as it ensures that the date manipulation functions are used correctly and consistently. Additionally, TypeScript’s type-checking capabilities can help prevent common pitfalls associated with date calculations.

Set Up TypeScript Environment

Before we dive into the code, let’s set up a basic TypeScript environment. If you haven’t already, you’ll need to install TypeScript and Node.js. Here are the steps:

  1. Install Node.js: Download and install Node.js.
  2. Install TypeScript: Open your terminal and run the following command:
   npm install -g typescript
  1. Initialize a TypeScript Project: Create a new directory for your project and navigate into it. Then, run:
   tsc --init

Basic Date Difference Calculation in TypeScript

To calculate the difference between two dates in days, you can use the getTime() method, which returns the number of milliseconds since January 1, 1970. By subtracting the timestamps of the two dates and converting the result into days, you can get the desired difference.

Here is a simple example:

const date1 = new Date('2025-03-01');
const date2 = new Date('2025-03-16');

const timeDiff = Math.abs(date2.getTime() - date1.getTime());
const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

console.log(`The difference between the two dates is ${diffDays} days.`);

Output:

Calculate Date difference in TypeScript

In this example, we have two dates: March 1, 2025, and March 16, 2025. The getTime() method is used to get the timestamps of these dates, and the difference is calculated by subtracting the two timestamps. The result is then divided by the number of milliseconds in a day to get the difference in days.

Check out: Get the Month from a Date in TypeScript

Handling Edge Cases to Calculate Dates in TypeScript

Daylight Saving Time (DST)

One of the challenges with date calculations is handling Daylight Saving Time (DST). If the dates you’re comparing span a DST change, the difference in hours may not be exactly 24 times the number of days. To handle this, you can use libraries like date-fns or moment.js, which provide more robust date manipulation functions.

Here is an example using date-fns:

import { differenceInDays } from 'date-fns';

const date1 = new Date('2025-04-01');
const date2 = new Date('2025-04-20');

const diffDays = differenceInDays(date2, date1);
console.log('The difference between the two dates is ${diffDays} days.');

Output:

Calculate Date difference in TypeScript using Date fns

The differenceInDays function from date-fns handles DST changes and other edge cases, providing a more accurate result.

Check out: Compare Dates Without Time in TypeScript

Time Zones

When working with dates, it’s important to consider time zones. If your application deals with users in different time zones, you need to ensure that the date calculations are consistent across all time zones. Using UTC dates can help avoid issues related to time zones.

Here’s an example of how to handle time zones using UTC dates:

const date1 = new Date(Date.UTC(2025, 3, 1));  // April 1, 2025 (month is 0-based)
const date2 = new Date(Date.UTC(2025, 3, 16)); // April 16, 2025

const timeDiff = Math.abs(date2.getTime() - date1.getTime());
const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

console.log(`The difference between the two dates is ${diffDays} days.`);

Output:

Calculate difference between dates in typescript

By using Date.UTC(), you create dates in the UTC time zone, which helps in avoiding time zone-related issues.

Real-World Example to Calculate Days Between Dates in TypeScript

Let’s consider a real-world example where you need to calculate the number of days left until a project deadline. Suppose you’re developing a project management tool for a tech company in New York. You want to display the number of days remaining until a project’s due date.

Here is how you can implement this:

interface Project {
    name: string;
    startDate: Date;
    endDate: Date;
}

const projects: Project[] = [
    {
        name: 'Website Redesign',
        startDate: new Date('2025-10-01'),
        endDate: new Date('2025-12-15')
    },
    {
        name: 'Mobile App Launch',
        startDate: new Date('2025-09-15'),
        endDate: new Date('2026-01-10')
    }
];

projects.forEach(project => {
    const today = new Date();
    const timeDiff = Math.abs(project.endDate.getTime() - today.getTime());
    const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

    console.log(`Project "${project.name}" has ${diffDays} days left until the deadline.`);
});

Output:

Calculate days between two date fields in TypeScript

In this example, we have an array of projects, each with a start date and an end date. We calculate the number of days remaining until each project’s end date and log the result.

Check out: Convert Number to Date in TypeScript

Best Practices

Use Libraries For Complex Calculations

For more complex date manipulations, consider using libraries like date-fns or moment.js. These libraries provide a wide range of functions for working with dates and times, handling edge cases, and ensuring accuracy.

Consistent Date Formats

Ensure that you use consistent date formats throughout your application. This helps in avoiding issues related to date parsing and formatting.

Testing

Thoroughly test your date calculations, especially if your application deals with critical dates like deadlines, schedules, or events. Write unit tests to cover different scenarios, including edge cases like DST changes and leap years.

Conclusion

In this tutorial, we have learned how to calculate the number of days between two dates in TypeScript using built-in methods. By working with the Date object and converting the time difference into days, we were able to achieve accurate results with minimal code.

This approach works well for most everyday use cases. However, if your application involves more complex date logic, like handling leap years, time zones, or recurring events, use utility libraries such as date-fns or dayjs to simplify those tasks.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.