Script 16.5 Using the DateTime Class

Using the DateTime class and jQuery DateTime Picker to select a date range in a form.

Output

Set the Start and End Dates of your life

Source
<?php # Script 16.5 - datetime.php

// Set the start and end date as today and tomorrow by default:
$start = new DateTime();
$end = new DateTime();
$end->modify('+1 day');

// Default format for displaying dates:
$format = 'm/d/Y';

// This function validates a provided date string.
// The function returns an array--month, day, year--if valid.
function validate_date($date) {
	
	// Break up the string into its parts:
	$array = explode('/', $date);
	
	// Return FALSE if there aren't 3 items:
	if (count($array) != 3) return false;
	
	// Return FALSE if it's not a valid date:
	if (!checkdate($array[0], $array[1], $array[2])) return false;

	// Return the array:
	return $array;
	
} // End of validate_date() function.

// Check for a form submission:
if (isset($_POST['start'], $_POST['end'])) {

	// Call the validation function on both dates:
	if ( (list($sm, $sd, $sy) = validate_date($_POST['start'])) && (list($em, $ed, $ey) = validate_date($_POST['end'])) ) {
		
		// If it's okay, adjust the DateTime objects:
		$start->setDate($sy, $sm, $sd);
		$end->setDate($ey, $em, $ed);
		
		// The start date must come first:
		if ($start < $end) {
			
			// Determine the interval:
			if(phpversion()>5.2) {
				$interval = $start->diff($end);
			} else {
				$interval->y = round(($end->format('U') - $start->format('U')) / (60*60*24*365));
			}
			
			
			// Print the results:
			echo "<p>Your life has been planned starting on {$start->format($format)} and ending on {$end->format($format)}.<br/> You will live";
			if($interval->y < 1) {
				echo ' less than 1 year.';
			} elseif($interval->y >=1) {
				echo " $interval->y year";
				echo ($interval->y >1)?"s.":'.'; 
			}
			
			
		} else { // End date must be later!
			echo '<p class="error">The starting date must precede the ending date.</p>';
		}
			
	} else { // An invalid date!
		echo '<p class="error">One or both of the submitted dates was invalid.</p>';
	}
		
} // End of form submission.

// Show the form:
?>
<h2>Set the Start and End Dates of your life</h2>
<form action="" method="post">
	<p>
		<label for="start">Start Date</label> 
		<input class="datepicker" type="text" name="start" value="<?php echo $start->format($format); ?>" />
	</p>
	<p>
		<label for="end">End Date</label>
		<input class="datepicker" type="text" name="end" value="<?php echo $end->format($format); ?>" />
	</p>
	
	<p>
		<input type="submit" value="Submit" />
	</p>
</form>