# [Solved-6 Solutions] Compare two dates with JavaScript - javascript tutorial

## Problem:

How to compare two dates with JavaScript ?

## Solution 1:

The following code defines how to compare two dates:

## Solution 2:

The `==`, `!=`, `===`, and `!==` operators are required to use `date.getTime()`

Checking for equality directly with the data objects won't work

## Solution 3:

The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date objects. Below three functions are used to find an object:

#### 1. dates.compare(a,b)

• Returns a number:
• -1 if a
• 0 if a = b
• 1 if a > b
• NaN if a or b is an illegal date

#### 2. dates.inRange(d,start,end)

• Returns a boolean or NaN:
• `true` if d is between the start and end (inclusive)
• `false` if d is before start or after end.
• NaN if one or more of the dates are illegal.

#### 3. dates.convert

• Used by the other functions to convert their input to a date object. The input can be
• A date-object : The input is returned.
• An array : Interpreted as [year,month,day]. [ Note: Month is 0-11 ].
• A number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
• A string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 01 2000" etc.
• An object : Interpreted as an object with year, month and date attributes.
Note : month is 0-11.

## Solution 4:

Compare `<` and` > `as normal, but anything involving `=` should use a `+` prefix.

Javascript get current date

## Solution 5:

`<` ` <=` ` >` `>=`these relational operators can be used to compare JavaScript dates:

However, the equality operators `==` `!=` `===` `!==` cannot be used to compare the dates because:

• Two distinct objects are never equal for either strict or abstract comparisons.
• An expression comparing Objects is only true if the operands reference the same Object.

We can compare the value of dates for equality using any of these methods:

## Solution 6:

This method is used to subtract from one date to other date.