When I first started using TypeScript, comparing dates felt confusing. I assumed I could just use == or === like I do with numbers or strings—but that didn’t work as expected.
In TypeScript (and JavaScript), dates are objects. So, if you compare two date objects directly, you’re actually comparing their references, not their values.
To properly compare dates, you need to compare their time values using methods like .getTime() or convert them into timestamps.
In this tutorial, I’ll show you the easiest ways to compare dates in TypeScript. In fact, I will show you five different methods to compare dates in TypeScript with examples.
But let’s first understand how TypeScript handles dates.
TypeScript uses JavaScript’s Date object, which represents a single moment in time. This makes date manipulation straightforward once you understand the basics.
The Date object internally stores time as the number of milliseconds since January 1, 1970, 00:00:00 UTC (the “Unix epoch”). This is why date comparisons work with operators – they’re actually comparing these millisecond values.
Now, let me show you various methods for comparing TypeScript dates.
Method 1: Using Comparison Operators
The simplest way to compare dates in TypeScript is by using standard comparison operators.
// Creating two date objects
const date1 = new Date('2025-04-24');
const date2 = new Date('2025-04-20');
// Comparing dates
if (date1 > date2) {
console.log('date1 is later than date2');
} else if (date1 < date2) {
console.log('date1 is earlier than date2');
} else {
console.log('Both dates are the same');
}
This works because Date objects are automatically converted to timestamps (milliseconds since January 1, 1970) when compared.
You can see the exact output in the screenshot below:

When you use operators like >, <, >=, <=, JavaScript implicitly calls the valueOf() method on the Date objects, which returns the timestamp in milliseconds. This makes comparison very intuitive.
I use this method when I need quick and readable code for date comparisons. It is especially useful in conditional statements, such as if-else blocks or ternary operators.
Check out Convert String to Date in TypeScript
Method 2: Using getTime() Method
For more explicit TypeScript date comparisons, I often use the getTime() method, which returns the timestamp in milliseconds.
Here is an example.
const date1 = new Date('2025-04-24');
const date2 = new Date('2025-01-15');
const time1 = date1.getTime();
const time2 = date2.getTime();
if (time1 > time2) {
console.log('date1 is later than date2');
} else if (time1 < time2) {
console.log('date1 is earlier than date2');
} else {
console.log('date1 and date2 are exactly the same time');
}
I find this method particularly useful when I need to store the timestamp for later use or when performing date arithmetic.
The getTime() method makes the code more explicit about what’s being compared.
You can see the output in the screenshot below:

This approach is also useful when you need to:
- Calculate time differences between dates
- Sort an array of dates
- Store timestamp values for database queries
- Implement custom date comparison logic
For example, to find the difference in days between two dates:
const date1 = new Date('2025-04-24');
const date2 = new Date('2025-01-15');
// Calculate difference in milliseconds
const diffInMs = Math.abs(date1.getTime() - date2.getTime());
// Convert to days
const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
console.log(`Difference: ${diffInDays} days`); // Shows the difference between dates
Method 3: Comparing String Dates
When working with dates that are returned as strings (such as from an API), you must first convert them to Date objects, as comparing string dates directly can yield incorrect results.
// Dates as strings
const dateStr1 = '2025-04-24';
const dateStr2 = '2025-04-20';
// Convert to Date objects
const date1 = new Date(dateStr1);
const date2 = new Date(dateStr2);
if (date1 > date2) {
console.log('date1 is later than date2');
} else {
console.log('date1 is earlier than or equal to date2');
}
String comparisons don’t work reliably for dates because they compare character by character. For example, comparing “2025-04-10” with “2025-04-02” would incorrectly show the second date as later because “2” comes after “1” in the day position.
You can see the exact output in the screenshot below:

This method is essential when working with:
- Form inputs where dates are entered as strings
- API responses that include date strings
- CSV or JSON data with date fields
Always validate that your string dates are in a format that the Date constructor can parse correctly. If you have dates in non-standard formats, you might need to manually parse them or use a library.
For more robust string date parsing, you can use this approach:
function parseAndCompareStringDates(dateStr1: string, dateStr2: string): number {
// Parse the date strings
const date1 = new Date(dateStr1);
const date2 = new Date(dateStr2);
// Check if dates are valid
if (isNaN(date1.getTime()) || isNaN(date2.getTime())) {
throw new Error('Invalid date format');
}
// Compare and return result: -1 (before), 0 (same), 1 (after)
return date1.getTime() === date2.getTime() ? 0 :
date1.getTime() > date2.getTime() ? 1 : -1;
}
// Usage
try {
const result = parseAndCompareStringDates('2025-04-24', '2025-04-20');
console.log(result > 0 ? 'First date is later' :
result < 0 ? 'First date is earlier' : 'Same date');
} catch (error) {
console.error('Error comparing dates:', error.message);
}
Check out Typescript sort array of objects by date descending
Method 4: Creating Helper Functions
In larger projects, I create helper functions to make date comparisons in TypeScript more readable:
function isLater(date1: Date, date2: Date): boolean {
return date1.getTime() > date2.getTime();
}
function isEarlier(date1: Date, date2: Date): boolean {
return date1.getTime() < date2.getTime();
}
function isSameDay(date1: Date, date2: Date): boolean {
return date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate();
}
function isWithinRange(date: Date, startDate: Date, endDate: Date): boolean {
return date.getTime() >= startDate.getTime() && date.getTime() <= endDate.getTime();
}
// Usage
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(isLater(tomorrow, today)); // true
console.log(isSameDay(today, today)); // true
In my experience, the isSameDay() function is particularly useful because it correctly compares just the date part, ignoring the time. This is important for many business applications where you only care about the day, not the exact time.
For date range checks, which are common in booking systems, event calendars, and reporting functions, the isWithinRange() function is invaluable:
// Check if a date falls within a booking period
const bookingDate = new Date('2025-07-15');
const seasonStart = new Date('2025-06-01');
const seasonEnd = new Date('2025-08-31');
if (isWithinRange(bookingDate, seasonStart, seasonEnd)) {
console.log('This date is available for summer bookings!');
} else {
console.log('This date is outside our summer booking period.');
}
Check out Convert Date to UTC in Typescript
Method 5: Using Date Libraries
For complex date operations, I often use libraries like date-fns or moment.js in TypeScript:
// Using date-fns (first install with: npm install date-fns)
import { isAfter, isBefore, isEqual, differenceInDays,
isWithinInterval, format, parse } from 'date-fns';
const date1 = new Date('2025-04-24');
const date2 = new Date('2025-04-20');
if (isAfter(date1, date2)) {
console.log('date1 is after date2');
} else if (isBefore(date1, date2)) {
console.log('date1 is before date2');
} else if (isEqual(date1, date2)) {
console.log('Both dates are the same');
}
// Calculate days between dates
const daysDifference = differenceInDays(date1, date2);
console.log(`There are ${daysDifference} days between the dates`);
// Check if a date is within a range
const isInRange = isWithinInterval(new Date('2025-04-22'), {
start: date2,
end: date1
});
console.log(`Date is within range: ${isInRange}`);
// Format and parse dates
const formattedDate = format(date1, 'MMM dd, yyyy');
console.log(`Formatted date: ${formattedDate}`);
// Parse a date from a specific format
const parsedDate = parse('Apr 24, 2025', 'MMM dd, yyyy', new Date());
console.log(`Parsed date:`, parsedDate);
These libraries provide powerful functions for comparing and manipulating dates.
When working on enterprise applications, I almost always reach for date-fns (or Luxon for newer projects) instead of using the native Date API. The productivity gains and reduced bugs are well worth the additional package size.
For example, date-fns makes it incredibly easy to perform common operations like adding business days (skipping weekends):
import { addBusinessDays, isWeekend, format } from 'date-fns';
// Calculate a due date that's 10 business days from now
const today = new Date();
const dueDate = addBusinessDays(today, 10);
console.log(`If you start today (${format(today, 'MMM dd')}), your deadline is ${format(dueDate, 'MMM dd, yyyy')}`);
// A simple business day filter function
function isBusinessDay(date: Date): boolean {
return !isWeekend(date);
}
Read Format Date with Timezone in Typescript
Comparing Dates with Different Time Zones
When dealing with dates from different timezones, be careful! The Date object in JavaScript converts everything to the local timezone.
// Creating a specific date in UTC
const utcDate = new Date(Date.UTC(2025, 3, 24)); // April 24, 2025 in UTC
// Getting the local date
const localDate = new Date(2025, 3, 24); // April 24, 2025 in local timezone
console.log('UTC date:', utcDate.toISOString());
console.log('Local date:', localDate.toISOString());
console.log('Are timestamps equal?', utcDate.getTime() === localDate.getTime()); // Likely false due to timezone difference
For timezone-aware comparisons, you might need to use additional libraries or the Intl API.
This is particularly important when dealing with:
- Applications that serve users across multiple time zones
- Event scheduling applications
- Conference calls or meeting planners
- Flight or hotel booking systems
Take a typical US business scenario: a company with offices in New York and San Francisco needs to coordinate meetings. The three-hour time difference can lead to confusion if not handled properly:
function formatDateForTimezone(date: Date, timeZone: string): string {
return new Intl.DateTimeFormat('en-US', {
timeZone,
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZoneName: 'short'
}).format(date);
}
// Meeting scheduled for 2pm ET
const meetingTime = new Date('2025-04-24T14:00:00-04:00'); // Eastern Time
console.log('Meeting time (ET):', formatDateForTimezone(meetingTime, 'America/New_York'));
console.log('Meeting time (PT):', formatDateForTimezone(meetingTime, 'America/Los_Angeles'));
Check out Check Date Less Than Today in Typescript
Practical Example: Finding Overdue Tasks
Here’s a practical example from a task management application I built:
interface Task {
id: number;
title: string;
dueDate: string;
completed: boolean;
}
function getOverdueTasks(tasks: Task[]): Task[] {
const today = new Date();
today.setHours(0, 0, 0, 0); // Reset time to start of day
return tasks.filter(task => {
if (task.completed) return false;
const dueDate = new Date(task.dueDate);
dueDate.setHours(0, 0, 0, 0); // Reset time for fair comparison
return dueDate < today;
});
}
// Example usage with USA-specific tasks
const tasks: Task[] = [
{ id: 1, title: "File Q1 Tax Report", dueDate: "2025-04-15", completed: false },
{ id: 2, title: "Prepare for July 4th Marketing Campaign", dueDate: "2025-06-15", completed: false },
{ id: 3, title: "Review Healthcare Benefits Options", dueDate: "2025-03-10", completed: true },
{ id: 4, title: "Black Friday Sale Planning", dueDate: "2025-10-15", completed: false },
{ id: 5, title: "Annual Team Performance Review", dueDate: "2025-02-28", completed: false }
];
const overdueTasks = getOverdueTasks(tasks);
console.log('Overdue Tasks:');
overdueTasks.forEach(task => {
console.log(`- ${task.title} (Due: ${task.dueDate})`);
});
This function finds all incomplete tasks with due dates in the past. I’ve used this pattern extensively in project management applications.
Notice how I reset the hours, minutes, seconds, and milliseconds to zero before comparing dates. This ensures we’re only comparing the date portions, not the time portions. Without this step, tasks due today might incorrectly show as overdue if the current time is earlier than the time component in the due date.
Important Points to Remember for Date Comparisons
Here are a few key points to remember when comparing dates in TypeScript.
- String Comparison: Never compare date strings directly. The string “2025-04-24” is not necessarily greater than “2025-04-20” in string comparison. JavaScript compares strings character by character, so “2025-04-24” > “2025-04-20” evaluates to false because “2” comes before “4” in the day position.
- Invalid Dates: Always validate date inputs. An invalid date input will result in an invalid Date object, which returns NaN for getTime().
function isValidDate(date: Date): boolean {
return !isNaN(date.getTime());
}
const validDate = new Date('2025-04-24');
const invalidDate = new Date('2025-13-45'); // Invalid month and day
console.log('Valid date check:', isValidDate(validDate)); // true
console.log('Invalid date check:', isValidDate(invalidDate)); // false
- Time Component: Remember that new Date() includes time down to milliseconds. For date-only comparisons, you might need to reset the time component.
function stripTime(date: Date): Date {
const result = new Date(date);
result.setHours(0, 0, 0, 0);
return result;
}
const date1 = stripTime(new Date('2025-04-24T14:30:00'));
const date2 = stripTime(new Date('2025-04-24T09:15:00'));
console.log('Same day (with time stripped):', date1.getTime() === date2.getTime()); // true because time is stripped
- Month Indexing: JavaScript’s Date object has zero-indexed months (0-11 instead of 1-12), which often leads to off-by-one errors.
// This creates December 15, 2025, not January 15, 2025
const incorrectDate = new Date(2025, 12, 15);
// This creates January 15, 2025
const correctDate = new Date(2025, 0, 15);
console.log('Incorrect date:', incorrectDate.toDateString()); // Shows a date in 2026
console.log('Correct date:', correctDate.toDateString()); // Shows Jan 15, 2025
- Daylight Saving Time: Be cautious when comparing dates around DST transitions. Adding days to a date can yield unexpected results.
// Create a date just before DST ends in the US (typically early November)
const beforeDST = new Date('2025-11-01T12:00:00');
// Add one day
const afterDST = new Date(beforeDST);
afterDST.setDate(beforeDST.getDate() + 1);
// The difference might not be exactly 24 hours
const diffInHours = (afterDST.getTime() - beforeDST.getTime()) / (1000 * 60 * 60);
console.log(`Difference in hours: ${diffInHours}`); // Might be 25 hours due to DST
I hope you now understand how to compare dates in TypeScript using various methods. For each method, I have provided a real-world example to help you better understand it.
Do let me know in the comments below if this tutorial helps you.
You may also like:
- How to Check If Date is Valid in Typescript?
- Subtract Days from Current Date in Typescript
- Get First and Last Day of Week in Typescript

Hey! I’m Bijay Kumar, founder of SPGuides.com and a Microsoft Business Applications MVP (Power Automate, Power Apps). I launched this site in 2020 because I truly enjoy working with SharePoint, Power Platform, and SharePoint Framework (SPFx), and wanted to share that passion through step-by-step tutorials, guides, and training videos. My mission is to help you learn these technologies so you can utilize SharePoint, enhance productivity, and potentially build business solutions along the way.