So I have an array of many images in it with their datetimes in the format Y-m-d H:i:s
And I wish to find the number of days between the image's date and the current date. This is where I have reached till now...and I'm getting a new error for every small change I make.
$myDateTime = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
$currentDate = $myDateTime->format('Y-m-d');
foreach($all_images as $key => $am){
$myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
$imageDate = $myDateTime1->format('Y-m-d');
$datediff=date_diff($currentDate,$imageDate);
echo $datediff;
}
I'm getting this error: Warning: date_diff() expects parameter 1 to be DateTimeInterface, string given
Any help would be appreciated! Thanks a lot!
What you've done is you've converted your values to Strings
before comparing them, so it's no longer comparing the difference between two dates but instead the difference between two strings. This is your error cause.
Solution:
The values you pass to date_diff
need to be two DateTime objects
as per the manual:
(PHP 5 >= 5.3.0, PHP 7)
DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects
Suggestion:
foreach($all_images as $key => $am){
$myDateTime1 = DateTime::createFromFormat('Y-m-d H:i:s', $am['datetime']);
$imageDate = $myDateTime1->format('Y-m-d');
$datediff=date_diff($myDateTime, $myDateTime1);
echo $datediff->format('%R%a days'); // +2 days
}
Note that the above date_diff
function takes Objects
not strings
.
This will now use date_diff
[procedurally in this example] to output a difference value $datediff
which you can use with DateTime formatting to reach the number of days/hours/whatever. Please Read the manual.