I am new in javascript so please be patient with me. I have an html code in which I have an html date input. I want to check with javascript if this date is before a specific date. How can i achieve that? And can the check be done before the user submits the form?(I mean can the check be done by the time the user selects the date and not after he hits the submit button cause after the date input there are more inputs before the form ends)
Asked
Active
Viewed 1,041 times
0
-
3Welcome to SO. Please post any code you have - ideally, show an attempt, or at least something you've looked into. Also, *search* for questions that may answer yours; yours is a very common question. Finally, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date – Mitya May 09 '17 at 09:35
-
1Check this http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript – shubham agrawal May 09 '17 at 09:35
1 Answers
1
Very simple, Date
instance can be compared directly.
$('.datepicker').datepicker({
dateFormat: 'dd-mm-yy',
numberOfMonths: 1,
onSelect: function(selected,evnt) {
compareTime(selected, time_you_want_to_compare);
}
});
function compareTime(time1, time2) {
return new Date(time1) > new Date(time2); // true if time1 is later
}
When you compare two Date
instance, or minus one another, the valueOf
method will be called internally, which convert the instance to timestamp (millisecond accurate).
function dateCompare(date1, date2){
return new Date(date2) > new Date(date1);
}
// Demo (uses jQuery)
$("tbody tr").each(function(){
$tr = $(this);
$td = $tr.children('td');
date1 = $td.eq(0).text();
date2 = $td.eq(1).text();
result = dateCompare(date1,date2);
$td.eq(2).text(result);
if($td.eq(2).text() == $td.eq(3).text()) $tr.css('background','green');
else $tr.css('background','red');
});
table{
border-collapse: collapse;
}
td{
padding: 5px;
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<thead>
<tr>
<td>date1</td>
<td>date2</td>
<td>Result</td>
<td>Expected</td>
</tr>
</thead>
<tbody>
<tr>
<td>01/12/2014</td>
<td>02/24/2014</td>
<td></td>
<td>true</td>
</tr>
<tr>
<td>01/12/2013</td>
<td>02/24/2012</td>
<td></td>
<td>false</td>
</tr>
<tr>
<td>01/12/2014</td>
<td>02/24/2018</td>
<td></td>
<td>true</td>
</tr>
<tr>
<td>01/12/2015</td>
<td>02/24/2011</td>
<td></td>
<td>false</td>
</tr>
</tbody>
</table>

Reda Maachi
- 853
- 6
- 15