简体   繁体   中英

Error when converting time to another format in PHP

I'm trying to change the time format here.

In the database, the time are saved as '0','1200','1300','1400','900', etc.

I want them to have a normal format like this: '0:00 AM', '12:00 PM', '1:00 PM', '2:00 PM', '9:00 AM'.

In the code I'm using :

$timeFormated = DateTime::createFromFormat('Gi', $myTime[$i]);
$newDateString = $timeFormated->format('g:i A'); 

However, I'm getting the error saying “Call to a member function format() on a non-object”.

Can anyone tell me what I did wrong here? Thanks!

It should work if you ensure your times are 4 digits.

You can do this by using:

$myTime = sprintf('%04d', $myTime);

So,

$timeFormated = DateTime::createFromFormat('Gi', '0'); // FALSE - doesn't work
$timeFormated = DateTime::createFromFormat('Gi', '0000'); // Works..!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM