0

I'm storing time as a string in my database... hopefully that's not my problem, I need to compare that stored time/date to the current time/date and get days/hours/minutes.

It's stored in this format... 11-10 07:42 PM

I assign that string to $storedTime.

$storedTime = "11-10 07:42 PM";

Get the current time like...

$now = new DateTime('now');

$now->setTimezone(new DateTimeZone('America/Los_Angeles'));

$now = $now->format('m-d h:i A');

Convert my variable to time like..

$time = new DateTime(strtotime($storedTime));

and format it...

$time1 = $time->format('m-d h:i A');

Try to compare the two times and I get an error that I'm still passing a string to diff()

$interval = $time1->diff($now);

echo $interval->format('%s second(s)');

I've tried sooo many different variations that my brain is fried lol help please :)

1 Answers1

0

When you call the ->format method on the DateTime class you are converting your object to a string. I believe this is where your problem lays.

See my example below to how this was solved. You can apply directly to your problem as you see fit.

$storedTime = "11-10 07:42 PM";
$convertedTime = DateTime::createFromFormat("m-d h:i A", $storedTime);
$convertedTime->setTimezone(new DateTimeZone('America/Los_Angeles'));

$now = new DateTime('now');
$now->setTimezone(new DateTimeZone('America/Los_Angeles'));

$diff = $convertedTime->diff($now);
$diff_string = $diff->format('%s second(s)');

print($diff_string);
Aidan Donnelly
  • 369
  • 5
  • 19
  • You nailed it. Thanks a lot, I appreciate it. I added `$elapsed = $diff->format('%a days %h hours %i minutes');` to get my final result of days and hours – droppedNboosted Nov 15 '21 at 20:18