w3resource

JavaScript: Comparison between two dates

JavaScript Datetime: Exercise-5 with Solution

Write a JavaScript function to compare dates (i.e. greater than, less than or equal to).

Test Data:
console.log(compare_dates(new Date('11/14/2013 00:00'), new Date('11/14/2013 00:00')));
console.log(compare_dates(new Date('11/14/2013 00:01'), new Date('11/14/2013 00:00')));
console.log(compare_dates(new Date('11/14/2013 00:00'), new Date('11/14/2013 00:01')));
Output :
"Date1 = Date2"
"Date1 > Date2"
"Date2 > Date1"

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Compare Dates</title>
</head>
<body>
</body>
</html>

JavaScript Code:

var compare_dates = function(date1,date2){
     if (date1>date2) return ("Date1 > Date2");
   else if (date1<date2) return ("Date2 > Date1");
   else return ("Date1 = Date2"); 
  }

console.log(compare_dates(new Date('11/14/2013 00:00'), new Date('11/14/2013 00:00')));
console.log(compare_dates(new Date('11/14/2013 00:01'), new Date('11/14/2013 00:00')));
console.log(compare_dates(new Date('11/14/2013 00:00'), new Date('11/14/2013 00:01')));

Sample Output:

Date1 = Date2
Date1 > Date2
Date2 > Date1

Flowchart:

Flowchart: JavaScript- Comparison between two dates

Live Demo:

See the Pen JavaScript - Comparison between two dates-date-ex- 5 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get the month name from a particular date.
Next: Write a JavaScript function to add specified minutes to a Date object.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Convert tabs to spaces, where each tab corresponds to count spaces

Example:

const tips_expandTabs = (str, count) => str.replace(/\t/g, ' '.repeat(count));
console.log(tips_expandTabs('\t\tw3resource', 4)); 

Output:

"        w3resource"