Subtracting Dates

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
polosport6699
Forum Commoner
Posts: 35
Joined: Wed Jun 11, 2003 3:19 pm

Subtracting Dates

Post by polosport6699 »

I have a simple function that Im sure has a simple solution. I have looked on the php.net website and found some things that are not working. I have two dates. I want to subtract date2 from date1 and calculate the days difference.

Code: Select all

$date1 = "2005-10-20";
$date2 = "2005-9-20"

$daydifference = ($date2 - $date1);
echo "daydifference = 31";
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

search this forum you should...answers you will find 8O

Code: Select all

<?
$date1 = "20/2/2005"; // dates in d/m/Y format
$date2 = "5/3/2005"; // dates in d/m/Y format
$date1 = explode("/",$date1);
$date2 = explode("/",$date2);
$date1 = date("m/d/Y", strtotime($date1[1]."/".$date1[0]."/".$date1[2]));
$date2 = date("m/d/Y", strtotime($date2[1]."/".$date2[0]."/".$date2[2]));
echo ((strtotime($date2) - strtotime($date1))/86400);
?>
from here: viewtopic.php?t=32137&start=0
polosport6699
Forum Commoner
Posts: 35
Joined: Wed Jun 11, 2003 3:19 pm

Post by polosport6699 »

Yeah I saw that but my date is formatted differently

my date is 2005-12-20. I tried modifying the code to use that format but it doesnt want to work...

Code: Select all

$date1 = "2005-12-20"; // dates in d/m/Y format
		$date2 = "2005-12-27"; // dates in d/m/Y format
		$date1 = explode("-",$date1);
		$date2 = explode("-",$date2);$date1 = date("y-m-d", strtotime($date1[1]."-".$date1[0]."-".$date1[2]));
		$date2 = date("y-m-d", strtotime($date2[1]."-".$date2[0]."-".$date2[2]));
		echo ((strtotime($date2) - strtotime($date1))/86400);
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

Code: Select all

$date1 = "2005-12-20"; 
$date2 = "2005-12-27";
echo ((strtotime($date2) - strtotime($date1))/86400);
Post Reply