'how to compare current date to a future date and validate it in javascript
`
`
I have a date text field in mm/dd/yyyy format. When a date is entered, I'd like to validate it to make sure the date is 2 months greater than the current date. If not, I'd like to display a message to notifying the user the date is less then 2 months but user can still proceed with filling the form after the notification.
Below is the form i want to add the function to.
Solution 1:[1]
If you used javascript then lets try to this one, It may help you.
<script type="text/javascript">
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDay();
var year = date.getYear();
var newdate = new Date(year,month,day);
mydate=new Date('2011-04-11');
console.log(newdate);
console.log(mydate)
if(newdate > mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Solution 2:[2]
If your date is in mm/dd/yyyy
format in string then you can use the following method. It will return true if date is 2 months greater than the current date and false otherwise -
// dateString in "mm/dd/yyyy" string format
function checkMonth(dateString)
{
var enteredMS = new Date(dateString).getTime();
var currentMS = new Date().getTime();
var twoMonthMS = new Date(new Date().setMonth(new Date().getMonth() + 2)).getTime();
if(enteredMS >= twoMonthMS)
{
return true;
}
return false;
}
Invoke this as checkMonth("03/12/2016");
Solution 3:[3]
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
Also you can do <,>,>=,<= etc
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Afroza Yasmin |
Solution 2 | |
Solution 3 | Basilin Joe |