user12920
user12920

Reputation: 301

Counting down days not showing the right number of days

I need help.. Is this right?

Start Date: Mar 16, 2014

End Date: Mar 19, 2014

Results: 2 Days

$plantEnd = get_the_author_meta('plantEnd', $sellerID );
$plantStart = get_the_author_meta('plantStart', $sellerID );

$future = $plantEnd;

$d = new DateTime($future);
echo $d->diff(new DateTime())->format('%a').' Days';

Why does it says 2 days? Isn't it 3 days? Im confused..

Upvotes: 1

Views: 52

Answers (2)

CrayonViolent
CrayonViolent

Reputation: 32517

Since you aren't actually using $plantStart in your code and instead using the current time, you're basically getting a difference between now (the time the script was run, on server's time zone) and the start of Mar 19, 2014 (0h:0m:0s). So what you are really getting is something like 2 days 5 hours 3 minutes 25 seconds (depending on when you run it vs. server time.

for example, when I run this locally:

$d->diff(new DateTime())->format('%d:%H:%i:%s');

I get 2:04:59:25

So there's more to it than just getting that "2" returned.. you're just not formatting for it.

And again, you aren't actually using the $plantStart anywhere either. So if you were to do this:

<?php
$plantEnd = '2014-03-19';//get_the_author_meta('plantEnd', $sellerID );
$plantStart = '2014-03-16'; //get_the_author_meta('plantStart', $sellerID );

$future = $plantEnd;

$d = new DateTime($future);
echo $d->diff(new DateTime($plantStart))->format('%d:%H:%i:%s');
?>

You will see it outputs 3:00:0:0 (or you could continue to just use %d and get the "3"). This is because $plantStart (presumably - based on your post) just specifies yyyy-mm-dd, so passing just the yyyy-mm-dd value will put the hh:mm:ss at 0:0:0 (beginning of day) , so it will be a full day's calculation, which has the effect of "rounding up" to the whole day increment.

Upvotes: 2

ShiningLight
ShiningLight

Reputation: 1143

I have a feeling that it's actually 2 days, someodd hours, and someodd minutes, or something to that effect. Because you're formatting to just do days, you're losing the nuances. I'd change the code to say "2.4 days" (and for the life of me I can't remember how I did this in the past...)

EDIT: in the past I have simply used date() instead of DateTime().

I did a little research, and you might want format('%d')." Days";

Upvotes: 1

Related Questions