---
# System prepended metadata

title: Compare Dates in JavaScript - Scaler Topics

---

---
title: How to Compare Two Dates With JavaScript? - Scaler Topics
description: This article by Scaler Topics deals with comparing two dates in JavaScript. Various ways to compare dates in javascript are discussed in depth, along with their examples.
author: Sakhi Bhagwat
category: JavaScript
---
:::section{.main}

There are some predefined ways to compare dates in javascript. To check the `date`, the first step is to create a date object using the `Date()` constructor. Then, we can check them using various ways- either using the comparison operators **`>`** or **`<`**, or by using the in-built `getTime()` function, which can directly check the two dates.
:::

:::section{.main}

## How to Perform Date Comparison With the Date Object in JavaScript

The JavaScript Date object is used to work with date and time. It allows us to create a new date with the specified date and time. The date can be in any format like **YYYY, MM, DD** or **YYYY-MM-DDTHH:MM: SSZ**, etc. 

**Syntax-** 
```javascript
new Date();
```

Using the comparison **operators > or <**, we can compare two dates in JavaScript. We can also use the `getTime()` function to compare dates in JavaScript. In the next section, we will discuss the above methods.

The date can be compared with the other date using **> or <**. We will check which date is before.
```javascript
var one = new Date(2021, 01, 15); //Year, Month, Date    
var two = new Date(2021, 02, 05); //Year, Month, Date    
if (one > two) {  //if the occurrence of date one is later, i.e., it is greater  
  console.log("Date one is greater than Date two.");    
}else { //if the occurrence of date two is later, i.e., it is greater 
  console.log("Date two is greater than Date one.");    
}
```
**Output-**
```javascript
Date two is greater than Date one.
```
:::

:::section{.main}

## How to Perform Equality Comparison With JavaScript

When comparing dates, we often use the getTime() method to ensure accuracy down to the millisecond. However, if we need to compare specific date components like day, month, or year, we rely on methods such as getDate(), getMonth(), and getFullYear().

Consider this example:

```javascript
//compare dates in javascript

let date1 = new Date();
let date2 = new Date("12/01/2021");

if (date1.getTime() === date2.getTime()) {
  console.log("Both dates are equal");
} else {
  console.log("The dates are not equal");
}
```
**Output:**
```plaintext
The dates are not equal
```
:::

:::section{.main}

## How to Perform Specific Date Comparisons

If we want to compare specific date values, like the day of the week, we can use the .getDay() date method. This method returns the day of the week as a number, where Sunday is 0, Monday is 1, and so on, up to Saturday is 6. 

```javascript
// compare dates in javascript

let date1 = new Date("12/12/2023").getDay();
let date2 = new Date("09/08/2024").getDay();

if (date1 < date2) {
  console.log("Date1 is earlier in the week than Date2");
} else if (date1 > date2) {
  console.log("Date1 is later in the week than Date2");
} else {
  console.log(`Both dates fall on the same day of the week`);
    
    
}

```

**Output:**

```plaintext
Date1 is later in the week than Date2
```
:::

:::section{.main}
## Examples


### Basic Date Comparison in JavaScript 

When comparing dates in JavaScript, the foundational approach involves utilizing the Date object alongside the getTime() method. This combination allows you to manipulate dates and times effectively by returning the number of milliseconds since the Unix Epoch, which serves as a reference point for date calculations.

```javascript
//code for date comparison in javascript

var date1 = new Date('2023-03-15');
var date2 = new Date('2023-05-20');

if (date1.getTime() < date2.getTime()) {
    console.log('Date1 is earlier than Date2');
} else {
    console.log('Date1 is later than Date2');
}
```

**Output:**
```plaintext
Date1 is earlier than Date2
```

#### Advantages and Potential Pitfalls
While this method is effective for basic comparisons, it may overlook nuances like time zones or diverse date formats. Let's dive into strategies to address these intricacies in the following section.


### Handling Time Zones and Formats

In JavaScript, when you're comparing dates, it's essential to remember time zones and various date formats. You can handle this using methods like toISOString() and toLocaleDateString().


```javascript
var date1 = new Date('2022-01-01T00:00:00Z'); // UTC time
var date2 = new Date('2022-01-01T00:00:00'); // Local time

console.log(date1.toISOString());
console.log(date2.toISOString());

```

**Output:**
```plaintext
2022-01-01T00:00:00.000Z
2022-01-01T00:00:00.000Z
```

### Dealing with Different Formats

The toLocaleDateString() method takes a Date object and returns a string representing the date portion, formatted according to the specified language and options. If no locale is provided, it defaults to the user's locale.

For instance, consider this example:

```javascript
const date = new Date('2024-02-11T00:00:00Z'); // UTC time

console.log(date.toLocaleDateString('de-DE')); // Outputs in German format
console.log(date.toLocaleDateString('en-US')); // Outputs in US format
```


**Output:**
```plaintext
11.2.2024
2/11/2024
```

### Using Moment.js for Date Comparison

Moment.js simplifies date handling in JavaScript by providing functions to compare dates easily. Whether you're working with past, present, or future dates, Moment.js makes it straightforward to compare and determine relationships between them.

```javascript
const moment = require('moment');

const startDate = moment('2023-01-01');
const endDate = moment('2023-12-01');

const isStartDateBeforeEndDate = startDate.isBefore(endDate);

console.log(`Is the start date before the end date? ${isStartDateBeforeEndDate}`);
```

**Output:**
```plaintext
Is the start date before the end date? true
```

### Using date-fns for Date Comparison

date-fns is like a Swiss Army knife for working with dates in JavaScript. It offers a range of handy functions that make it easy to compare, manipulate, and format dates. Whether you need to check if one date is before another, add or subtract time intervals, or format a date in a specific way, date-fns has got you covered. It's a modern and reliable tool for anyone dealing with dates in their JavaScript projects.


```javascript
// Importing necessary functions from date-fns library
const { isBefore, parseISO } = require('date-fns');

// Defining two dates to compare
const date1String = '2023-02-11';
const date2String = '2023-11-11';

// Parsing the date strings into date objects
const date1 = parseISO(date1String);
const date2 = parseISO(date2String);

// Comparing the dates to see if the date1 comes before the date2
const isDate1BeforeDate2 = isBefore(date1, date2);

// Outputting the result
console.log(`Is date1 (${date1String}) before date2 (${date2String})? ${isDate1BeforeDate2}`);

```

**Output:**
```plaintext
Is date1 (2023-02-11) before date2 (2023-11-11)? true
```

:::

:::section{.main}

## JavaScript Date Methods

JavaScript provides several helpful methods for working with comparing dates. These methods allow you to manipulate, format, and extract information from date objects. 



| Method of Date Object | Description |
|:---------------------:| :-----------: |
|       `getDate()`       |   This method returns the day of the month from 1-31 for the given date according to the **local time**.          |
|       `getDay()`        |  This method is used to return the **day of the week from 0-6** for the given date according to the local time.           |
|     `getFullYear()`     |   This method returns the year, which is a **4-digit number** for the given date according to the local time.          |
|      `getHours()`      |   This method is used to return the hour of the specified date from **0-23** for the given date according to the local time.          |
|   `getMilliseconds()`   |   This method is used to return the millisecond from **0-999** for the given date according to the local time.           |
|     `getMinutes()`     |    This method is used to return the minutes from **0-59 for the given date** according to the local time.          |
|      `getMonth()`       | This method is used to return the month from **0-11 for the given date** according to the local time.             |
|     `get seconds()`     |   This method returns the second of the given date **from 0-59 for the given date** according to the **local time**.           |
|       `getTime()`       |  This method returns the numeric value of the given date as the number of milliseconds that have elapsed since **January 1, 1970, 00:00:00 UTC**.          |
|  `getTimezoneOffset()`  |    This method is used to return the time zone **offset in minutes**.         |
|     `getUTCDate()`      |  This method returns the day of the month from **1-31** for the given date according to the universal time.           |
|      `getUTCDay()`      |  This method returns the day of the week from **0-6** for the given date according to the universal time.           |
|   `getUTCFullYear()`    |  This method returns the year, which is a **4-digit number** for the given date according to the **universal time**.           |
|     `getUTCHours()`     |  This method is used to return the hour from **0-23 for the given date** according to the **universal time**.           |
| `getUTCMilliseconds()`  |     This method is used to return **milliseconds from 0-999** for the given date according to the **universal time**.        |
|    `getUTCMinutes()`    |  This method is used to return the **minutes from 0-59** for the given date according to the universal time.           |
|     `getUTCMonth()`     | This method is used to return the **month from 0-11** for the given date according to the universal time.             |
|    `getUTCSeconds()`    |   This method returns the seconds of the given **date from 0-59** for the given date according to the **universal time**.          |
|      `getYear()`       |  This method is used to return the year but in **2-3** digits so use `getFullYear()` method.           |
|       `setDate()`       | This method is used to set the day of the **month from 1-31** for the given date according to the local time.            |
|     `setFullYear()`    |  This method is used to set the year, a **4-digit number** for the given date according to the local time.       |
|      `setHours()`       |  This method is used to set the hours of the specified date from **0-23** for the given date according to the **local time**.           |
|   `setMilliseconds()`   |   This method is used to set the millisecond from **0-999** for the given date according to the local time.          |
|     `setMinutes()`      |  This method is used to set the minutes from **0-59** for the given date according to the local time.           |
|      `setMonth()`       | This method sets the month from 0-11 for the given date according to the local time.            |
|     `setSeconds()`      | This method is used to set the seconds of the given **date from 0-59** for the given date according to the local time.            |
|       `setTime()`       |  This method is used to set the numeric value of the given date as the number of milliseconds that have elapsed since **January 1, 1970, 00:00:00 UTC**.           |
|     `setUTCDate()`      |  This method sets the day of the month from 1 to 31 for the given date according to the universal time.           |
|   `setUTCFullYear()`    |   This method is used to set the year, a **4-digit** number for the given date according to the universal time.          |
|     `setUTCHours()`     | This method is used to set the hour from **0-23** for the given date according to the universal time.            |
| `setUTCMilliseconds()`  |  This method is used to set milliseconds from **0-999** for the given date according to the universal time.           |
|    `setUTCMinutes()`    |  This method is used to set the minutes from **0-59** for the given date according to the **universal time**.           |
|     `setUTCMonth()`     | This method sets the month from 0-11 for the given date according to the **universal time**.            |
|    `setUTCSeconds()`    | This method is used to set the seconds of the given date from **0-59 for **the given date according to the universal time.           |
|       `setYear()`      |  This method is used to set the year but in `2-3` digits, so use the `setFullYear()` method.           |
|    `toDateString()`    |  It is used to return the **"date"** portion in the form of the string which is **human-readable**.           |

:::

:::section{.main}

## The Unix Epoch and Time Zones

JavaScript's Date object operates within the framework of the Unix Epoch, which marks the beginning of time as 00:00:00 UTC on January 1, 1970. This standardizes time computations across platforms. 

Time zones define regions with the same standard time, and while JavaScript defaults to the local time zone, it can also handle UTC or any other time zone. Understanding these basics about the Date object and time zones will enhance your ability to compare dates effectively.

:::

:::section{.main}

## The Relevance and Applications of Date Comparison

JavaScript's date comparison capabilities extend beyond simply determining which date comes before or after another. Instead, it empowers developers to handle and manipulate time effectively, opening up a world of possibilities across various applications.


### Scheduling Tasks

For instance, JavaScript's date comparison capabilities allow developers to automate processes based on specific dates and times when scheduling tasks. This feature is invaluable for ensuring the timely execution of critical operations.

### Creating Calendars

Moreover, the creation of calendars heavily relies on date comparison. By accurately comparing dates, developers can determine essential calendar details such as the number of days in a month or the day of the week a month begins on. This functionality is crucial for building intuitive and user-friendly calendar applications.


### Exploring Related Concepts

Furthermore, beyond simple date comparison, JavaScript also offers date manipulation and formatting functionalities. These capabilities enable developers to perform advanced operations, such as adding or subtracting days, months, or years from a date and displaying dates in various formats tailored to user preferences.
:::

:::section{.summary}

## Conclusion
* JavaScript provides the Date object for working with dates and times, allowing us to create specific dates and times.
* Date objects in JavaScript offer methods such as getFullYear(), getMonth(), and getTime() to manipulate and format dates according to our requirements.
* Comparison operators like > or < can be used to compare dates in JavaScript, while the getTime() method directly compares two dates.
* The Date object provides versatility in handling date and time operations, making it a powerful tool for working with temporal data in JavaScript.
:::