简体   繁体   中英

PHP - Converting a string written to a variable to a time format

So I am pulling some data from a internal jsp page with DOMDocument and using a php script to insert that into a database. It pulls the data and I have so far got everything the way I want it, but the time that is output on the page, which is in a string format is in the following format:

12:05:00a //for am
10:15:00p //for pm, obviously

I was thinking I could use strtotime (but I'm open to suggestions). Here is how it is coded:

$cols = $row->getElementsByTagName('td');
$scheduled_time = $cols->item(0)->nodeValue;
echo $scheduled_time;

I know the answer probably very easy, but I haven't had to work much with converting times. It can be in military time as well.

Thanks in advance.

You already have a time format. '12:05:00' is fine for inserting into a time field. You do however have an issue witha that last character, determining AM from a , and PM from p .

So, just sort that with a str_replace() ;

$replaceFrom = array('a', 'p');
$replaceTo   = array(' AM',' PM');

$time = str_replace($replaceFrom,$replaceTo,$scheduled_time);
echo date("H:i", strtotime($time));

Try with this

echo date("G:i", strtotime($time));

or you can try like this also

echo date("H:i", strtotime("10:15 PM"));

also, you can try to do this

$date = new \DateTime();
echo date_format($date, 'Y-m-d H:i:s');
#output: 2015-09-14 10:15:00

echo date_format($date, 'G:ia');
#output: 10:15pm

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