Jump to content

DateTime - counting days between two dates


bannerke

Recommended Posts

Hi,

 

Here is my code:

 

$today = new DateTime("now");
$date2 = new DateTime($row["Date"]);
echo "\n";
echo $today->format("Y-m-d");
echo "\n";
echo $date2->format("Y-m-d");
echo "\n";
$days = $date2->diff($today);
$echo $days->format("%a");

 

the $row["Date] is a datetime object retrieved from a mysql database.

 

The result of the code is:

2015-02-24

2015-02-23

0

 

I don't understand why it keeps returning me 0. When I make a new DateTime("2015-02-23") and I use the diff function on this, it returns 1...

 

How can I solve this?

 

Thanks!

The following might help you out:

 

(Reading you're post again, I see you're pulling it from a database table, there are ways of doing that directly from MySQL also. I am sure some guru here will help you with that.)

 

Though you can do it in PHP like this:

<?php
function number_of_days($date) {
	$today = new DateTime();
	$future = new DateTime($date);
	
	$difference = $future->diff($today, true);
	echo "There are " . $difference->days . " days till the Detroit Tigers opening day!";
}

number_of_days("2015-04-06 13:08:00");

The result of the code is:

2015-02-24

2015-02-23

0

 

I don't understand why it keeps returning me 0. When I make a new DateTime("2015-02-23") and I use the diff function on this, it returns 1...

 

 

Does your $row["Date"] variable contain the time of day? The two dates are probably less then a day apart based on time.

 

You could try displaying the DateTime objects using something like this:

$today = new DateTime("now");
$date2 = new DateTime($row["Date"]);
 
print '<pre>' . print_r($today, true) . '</pre>';
print '<pre>' . print_r($date2, true) . '</pre>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.