Hello all!

I recently did a small project for a friend. What the project does is take two birth dates. It calculates the date when the older person is twice the age of the younger person. I've tried it with several dates and confirmed correct results with timeanddate.com, so the code appears to work. I was wondering if anyone could see any glaring issues with my code.

if(isset($_GET['younger']) && isset($_GET['older']))
{
	//Ensure we're working with valid dates
	$younger_arr = explode('-', $_GET['younger']);
	$older_arr = explode('-', $_GET['older']);

if(!is_array($younger_arr) || !is_array($older_arr))
{
	echo json_encode(array('response' => false, 'message' => '<div class="error">Please enter a properly formatted date.</div>'));
	exit;
}

if(!checkdate($younger_arr[0], $younger_arr[1], $younger_arr[2]))
{
	echo json_encode(array('response' => false, 'message' => '<div class="error">Please enter a correct date for Person 1.</div>'));
	exit;
}

if(!checkdate($older_arr[0], $older_arr[1], $older_arr[2]))
{
	echo json_encode(array('response' => false, 'message' => '<div class="error">Please enter a correct date for Person 2.</div>'));
	exit;
}

$older = new DateTime($older_arr[2].'-'.$older_arr[0].'-'.$older_arr[1]);
$younger = new DateTime($younger_arr[2].'-'.$younger_arr[0].'-'.$younger_arr[1]);

//Ensure Person 1 is younger than Person 2
if($older >= $younger)
{
	echo json_encode(array('response' => false, 'message' => '<div class="error">Person 2 must be older than Person 1.</div>'));
	exit;
}

//Calculate how old in days Person 2 is when Person 1 is born
$days = floor((strtotime($younger_arr[2].'-'.$younger_arr[0].'-'.$younger_arr[1]) - strtotime($older_arr[2].'-'.$older_arr[0].'-'.$older_arr[1])) / (60 * 60 * 24));

//Add the days to Person 1's date of birth for the final date
$younger->modify('+'.$days.' days');

echo json_encode(array('response' => true, 'result' => $younger->format('F j, Y')));
}
else
{
	$array = array('response' => false,
				   'message' => '<div class="error">Sorry, there was an error getting the date. Please try again.</div>');
	echo json_encode($array);
}

The script receives the values from an AJAX call. Please note I am running an older version of PHP (5.2.9) so I don't have full capabilities of the DateTime class, otherwise I would have used the DateTime::add and DateTime::diff methods and made my code generally nicer.

If anyone has any comments I would greatly appreciate it. Thanks! 🙂

    Write a Reply...