Link to home
Start Free TrialLog in
Avatar of Daniel Pineault
Daniel Pineault

asked on

Extract Time component from DateTime field using PHP

I'm trying to extract the Time from a DateTime field, but when I do so I always get 7:00 PM or 19:00 depending on the format I choose and I can't figure out why.

echo $modelLeg->StartDtTime.' '.strtotime($modelLeg->StartDtTime).' '.date("H:i:s", strtotime($modelLeg->StartDtTime))

Open in new window


This returns

1899-12-30 00:00:00 19:00:00
1899-12-30 00:00:00 19:00:00
1899-12-30 09:30:00 19:00:00
1899-12-30 09:30:00 19:00:00
1899-12-30 11:00:00 19:00:00
1899-12-30 08:00:00 19:00:00
1899-12-30 08:00:00 19:00:00

So, strtotime() recognizes the Time properly, but when I add in the date("H:i:s"...) aspect it errs for some reason.  Could someone explain why and what I am doing wrong.

Thank you!


Update:
I kept playing, researching and I have managed to get it to work by doing

$date = DateTime::createFromFormat('Y-m-d H:i:s', $modelLeg->StartDtTime);
echo $date->format("g:i A");

Open in new window


but as a novice PHP programmer I'd still like to understand and learn why what I was doing previous wasn't working and if this new code is truly a good solution.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Daniel Pineault
Daniel Pineault

ASKER

Thank you for the solution, but more importantly the explanation!
No worries :)