hello sir..i am wondering how to calculate between two dates..here is my code:

<input type="text" name"date1" value="mm/dd/yyyy">
<input type="text" name"date2" value="mm/dd/yyyy">
<input type="submit" name"calculate" value="calculate">
<?php echo $answer;?>

example value of date1 is 09/26/2010
example value of date2 is 09/27/2010
so the answer should be 1 by subtracting date2 to date1

i hope you can help me with learning php..thanks daniweb -aizel

Dani AI

Generated

wanted the day difference between two dates and ’s timestamp/mktime reply provides a straightforward, working solution for simple inputs. That approach is fine for quick tests, but it skips validation, can be brittle with different input formats, and may be affected by server timezones and daylight‑savings if times are involved. A DateTime/DateInterval approach is clearer, safer, and easier to validate or extend.

Common pitfalls to keep in mind: ambiguous formats (mm/dd vs dd/mm), invalid user input, whether the count should be inclusive (count both endpoints) or exclusive, and whether time-of-day or timezone should matter. DateTime::createFromFormat lets parsing be explicit and DateInterval->days gives the total-day difference without manual math.

Example (detects mm/dd/yyyy or ISO yyyy-mm-dd, validates, preserves sign):

<?php
if (!empty($_POST['calculate'])) {
    $raw1 = trim($_POST['date1'] ?? '');
    $raw2 = trim($_POST['date2'] ?? '');

    $fmt = function($s) { return (strpos($s, '/') !== false) ? '!m/d/Y' : '!Y-m-d'; };
    $tz = new DateTimeZone('UTC'); // use UTC for pure date math to avoid DST surprises

    $d1 = DateTime::createFromFormat($fmt($raw1), $raw1, $tz);
    $err = DateTime::getLastErrors();
    if (!$d1 || $err['error_count'] || $err['warning_count']) { $answer = 'Invalid first date'; }
    else {
        $d2 = DateTime::createFromFormat($fmt($raw2), $raw2, $tz);
        $err = DateTime::getLastErrors();
        if (!$d2 || $err['error_count'] || $err['warning_count']) { $answer = 'Invalid second date'; }
        else {
            $interval = $d1->diff($d2);
            $days = $interval->days;           // total days (non-negative)
            $sign = $interval->invert ? '-' : '';
            $answer = $sign . $days . ' days';
            // inclusive count (both endpoints): $days + 1
        }
    }
}
?>

Notes: HTML5 <input type="date"> sends ISO YYYY-MM-DD, which DateTime parses easily. For hour/minute precision include times in the format and avoid forcing UTC if local business time matters. For quick learning, ’s method works; for production code, prefer DateTime/explicit parsing and validation.

Recommended Answers

All 4 Replies

Here is complete code what you need.
Hope it will help you.

<?php

	if(isset($_REQUEST['calculate']))
	{
		$temp1 = explode('/',$_REQUEST['date1']);
		$date1 = mktime(0,0,0,$temp1[0],$temp1[1],$temp1[2]);
		
		$temp2 = explode('/',$_REQUEST['date2']);
		$date2 = mktime(0,0,0,$temp2[0],$temp2[1],$temp2[2]);
		
		$dateDiff = $date2 - $date1;
		$fullDays = floor($dateDiff/(60*60*24));
		$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
		$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
		$answer = "Differernce between date2 and date1 is :  $fullDays days, $fullHours hours and $fullMinutes minutes.";
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form method="post">
date1 : <input name="date1" type="text" value="<?=$_REQUEST['date1'];?>">
date2 : <input name="date2" type="text" value="<?=$_REQUEST['date2'];?>">
<input type="submit" name="calculate" value="calculate">
<br />
<br />
<?php echo $answer;?>
</form>
</body>
</html>

it works like a charm :D thanks for the help sir..

I am not sir.. i am mam :) I think i should rename my profile name.

commented: superb coading sir even i can calculate number of days from my birth +0

superb coading sir even i can calculate number of days from my birth

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.