Javatpoint Logo
Javatpoint Logo

Javascript Compare dates

In the previous section, we discussed the date methods as well as the constructors.

Here, with the help of those methods, we will learn to compare dates.

Basically, there are different ways by which we can compare dates, such as:

  1. Comparing two dates with one another.
  2. Comparing date with time.
  3. Comparing dates using getTime()

Comparing two dates with one another

Example:

Test it Now

Comparing date with time

Example 1: Comparing different dates with different timings

Test it Now

Example2: Comparing same dates with disimilar timings

Test it Now

Comparing date with getTime()

A better approach to make comparison between dates is to use getTime() function. This function lets converting date into numeric value to directly compare them.

Example1: Comparing current date and time with a given date and time.

Test it Now

Example2: Comparing two different dates with different timings.

Test it Now

Thus, we can compare dates in many possible ways.

Changing Date Format

We can also change or set the format through JavaScript code. The function getFullYear(), GetMonth(), and getDate() allows to set the format of date accordingly.

Example1: Changing the date format to 'yyyy-mm-dd'.

Test it Now

We can also set the date and time format according to our need.

Example2: Changing the datetime format to 'yyyy-dd-mm hh:mm:ss'.

Test it Now




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA