Domanda

Banging my head against the wall today working with dates. I am looping through a bunch of datetimes and comparing them to the current date to determine how far away they are.

So I am returning things like 'tomorow @ 4pm' , 'yesterday at 3pm', 'today at 12pm' , '3 days ago', 'in 3 days' etc.

It all works fine until it gets to around today/tomorow/yesterday.

Date diff is returning silly things like -0 and +0 when it gets to these dates. My theory is that dates that are lets say... 23 hours in the future, or even 10 hours in the future, even if they take place on the 'next day' are returning as 0 instead of 1.

Unfortunately date_diff doesn't appear to return decimals or allow me to do any sort of rounding.

Here is some sample code:

$difference = $meeting_date->diff($current_date);
$difference = $difference->format('%R%a');

I then check this difference integer to see if it is 0, -1, 1, < -1, or > 1. I handle the preceding + sign where necessary.

The ones that are supposed to be -1 or +1, are sometimes returning as -0 or +0 (..what?)

Also, -0 is not = 0, but is apparently less then -1 according to PHP.

S.O.S, someone help.

I have read all the related questions, this is not a duplicate and it is not related to that random 6015 error. Also using diff->days is not the answer. This always returns an absolute and not negatives which would be a problem.

È stato utile?

Soluzione

Hm... My approach here would be to split the time and date display. Something like this:

$meeting_day = DateTime::createFromFormat($meeting_date->format('Y-m-d'));

// set $today to today's date at 0:00

$diff = $meeting_day->diff($today);

That should give you a useable day-based difference (for rendering today, yesterday, tomorrow etc.).

Altri suggerimenti

Instead of comparing days, why not compare time() to another datetime which you can format using strtotime()

time()

You can convert whatever datetime you're comparing to with strtotime()

strtotime()

And now you can compare the difference in the two in seconds and divide as you see fit for days, hours etc

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top