troubleshooting Question

Extract Time component from DateTime field using PHP

Avatar of Daniel Pineault
Daniel Pineault asked on
PHP* datetime
3 Comments1 Solution122 ViewsLast Modified:
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))

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

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.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 3 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros