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.
Let’s create some examples to compare two dates.
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; } }
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>
The MomentJS provides the following methods to compare dates with or without a timestamp.
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
This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More
in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More
View Comments
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