In this JavaScript tutorial, We will learn the comparison of two dates using javascript, this is a very common problem in web development. I am using Date()
class to convert date and store into the variable, finally comparing those dates and alert messages.
Two dates can be compared by converting them to numeric values that correspond to their times. To begin, we’ll use the getTime() function to convert the Date to a numerical value.
Method to Compare two date in JavaScript
Let’s create some examples to compare two dates.
Example 1: Compare two Dates Using JavaScript and jQuery
We are using jquery to get input values from the text input and then comparing using getTime().
function validate() { var startDate = new Date(jQuery('#from').val().replace(/-/g, '/')).getTime(); var endDate = new Date(jQuery('#to').val().replace(/-/g, '/')).getTime(); var date = new Date(); var currentDate = new Date(date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear()).getTime(); if (startDate > endDate){ alert('From date is greater than To date'); return false; } else if (startDate > currentDate || endDate > currentDate) { alert('You have entered future date'); } else { return true; } }
Example 2: Compare two dates Using Javascript
We are using pure js method to compare two dates.
<script> // Current Date var g1 = new Date(); var g2 = new Date(); if (g1.getTime() === g2.getTime()) document.write("Both dates are equal"); else document.write("Not equal"); javascript: ; </script>
Example 3: Compare dates Using MomentJS
The MomentJS provides the following methods to compare dates with or without a timestamp.
- isSame: Checks two-moment date objects are equal or not.
- isBefore: One date is before another date
- isAfter: one date is after another date
Sample Example:
moment('2022-01-22').isSame('2022-01-12'); // false moment('2022-01-22').isBefore('2022-01-12'); // false moment('2022-01-22').isAfter('2022-01-12'); // true
Thanks. Its working fine for me.I am new to this environment. But i faced one issue like, if i enter any wrong date its showing error and again i am updating wrong date that time also error message is again showing one more time. Can you help to solve this problem.
you can use try catch