Jump to content

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");
Edited by Strider64

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>';

Or you can just do a var_dump($difference); or whatever variable you have for the dfference to see the different options besides the difference in days. I believe $difference->h would be hours? 

Edited by Strider64
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.