Reputation: 105
I have two types of date, I need to check the end date should greater than start date.
These are two input:
<input id="startdate" type="date" name="startdate" />
<input id="enddate" type="date" name="enddate" />
<div class="errmsg" id="errmsg"></div>
I need if the end date less than start date (show error message in errmsg div)
Upvotes: 1
Views: 2490
Reputation: 38584
You can use checkdate ()
for date validate checkdate php.net
$date = $_POST['enddate'];
$test_date = explode('/', $date);
if (count($test_date) == 3)
{
if (checkdate($test_date[0], $test_date[1], $test_date[2])) {
// date is valid
}
else
{
// Invalid date dates
}
} else
{
// invalid input
}
And to compare two date
$today_dt = strtotime($_POST['startdate']);
$expire_dt = strtotime($_POST['enddate']);
if ($expire_dt < $today_dt)
{
/* Do something */
}
Upvotes: 0
Reputation: 3385
You can use strtotime for html5 input date type
<?php
$startdate= $_POST['startdate'];
$enddate= $_POST['enddate'];
$start = strtotime($startdate);
$end = strtotime($enddate);
if($end < $start){
//show error
}
?>
Upvotes: 1
Reputation: 694
$startdate = strtotime($_POST['startdate']);
$enddate = strtotime($_POST['enddate']);
if ($enddate < $startdate) {
$error = 'Error!';
}
echo $error;
Upvotes: 2
Reputation: 324
A suggestion here:
First, your input could be located in a form:
<form action='action_code.php' method="post">
<input id="startdate" type="date" name="startdate" />
<input id="enddate" type="date" name="enddate" />
<input type="submit" value="Submit">
</form>
and the action_code.php file would contain:
<?php
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
if($enddate < $startdate){
echo 'enddate has to be after startdate';
}else{
echo 'form submitted';
echo $startdate;
echo $enddate;
}
echo '<a href="/home.php">Back home</a>';
?>
What is to retain here is that dates can be compared using comparison operators likewise numbers. I omitted any formatting in order to keep the code clean.
Upvotes: 0
Reputation: 4160
use jquery as
$("#enddate").keyup(function(){
var startDate = $('#startdate').val().replace('-','/');
var endDate = $('#enddate').val().replace('-','/');
if(startDate > endDate){
$('#errmsg').html('Start time must be smaller than End time');
}else{
$('#errmsg').html('');
}
});
Upvotes: -1