Comparing stored time string to DateTime('now')

323 Views Asked by At

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

There are 1 best solutions below

1
Aidan Donnelly On BEST ANSWER

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