Today’s script will be much useful to you and i hope interesting as well. ie., PHP Script to find days between two selected dates.
Let’s see the PHP script (find_days() function):
//this function return two main values status (either true or false) and result (which has all the other details)
function find_days($start_date, $end_date) {
$response = new stdClass();
//using try catch in case if any invalid date entered
try {
//get the entered start date and end date and convert into datetime
$sdate = new DateTime($start_date);
$edate = new DateTime($end_date);
//here is the real deal, diff() is the function which is going to give us the result
$dateInterval = $edate->diff($sdate);
$response->status = true;
$response->result = $dateInterval;
return $response;
} catch (Exception $e) {
$response->status = false;
$response->result = 'Invalid Date Format';
return $response;
}
}Read the comments in the script to understand it. You can use it in your existing projects as well.
Basically the above function will receive two parameters “$start_date” and “$end_date” and then converts into DateTime object using DateTime(). And diff() will return the difference between two dates.
Here is the demo script shows you how to use the above function:
<?php
//this function return two main values status (either true or false) and result (which has all the other details)
function find_days($start_date, $end_date) {
$response = new stdClass();
//using try catch in case if any invalid date entered
try {
//get the entered start date and end date and convert into datetime
$sdate = new DateTime($start_date);
$edate = new DateTime($end_date);
//here is the real deal, diff() is the function which is going to give us the result
$dateInterval = $edate->diff($sdate);
$response->status = true;
$response->result = $dateInterval;
return $response;
} catch (Exception $e) {
$response->status = false;
$response->result = 'Invalid Date Format';
return $response;
}
}
?>
<html>
<head>
<title>PHP Script to find Days between two Dates!</title>
</head>
<body>
<h3>Days between two Dates</h3>
<form method="post">
Start Date: <input type="date" name="sdate" placeholder="eg:16-05-2016" value="<?= (isset($_POST['sdate'])) ? $_POST['sdate'] : date('Y-m-j'); ?>" />
End Date: <input type="date" name="edate" placeholder="eg:16-05-2016" value="<?= (isset($_POST['edate'])) ? $_POST['edate'] : date('Y-m-j', strtotime('+ 3 days')); ?>" />
<input type="submit" value="Find Days" /><br /><br />
<?php
//check if the post data has some value
if (isset($_POST['sdate']) && $_POST['sdate']) {
$start_date = $_POST['sdate'];
$end_date = $_POST['edate'];
//now call the function
$days_array = find_days($start_date, $end_date);
if ($days_array->status) {
echo "Result: <b>".$days_array->result->days."</b> Days";
} else {
echo $days_array->result;
}
}
?>
</form>
</body>
</html>You can also see the online demo of this script from the below link:

nice job,thank