1

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)

Grokify
  • 15,092
  • 6
  • 60
  • 81

5 Answers5

2
$startdate = strtotime($_POST['startdate']);
$enddate = strtotime($_POST['enddate']);

if ($enddate < $startdate) {
$error = 'Error!';
}

echo $error;
zeropsi
  • 682
  • 9
  • 24
1

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
    }
?>
Onimusha
  • 3,348
  • 2
  • 26
  • 32
0

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.

Vincent Labrecque
  • 304
  • 1
  • 5
  • 12
0

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 */
}

Refer this answer

Community
  • 1
  • 1
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
-1

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('');
}
});
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
Double H
  • 4,120
  • 1
  • 15
  • 26