Format value with explode and PHP implode

4

I have a dhEmi tag that has this value 2016-09-09T08:10:52-03:00

To return a datetime I did the following.

$dtemis = $item->infNFe->ide->dhEmi;

$res = explode("T", $dtemis);
$res1 = explode("-03:00", $res[1]);

$array = array ($res[0],$res1[0]);
$dtemisformat = implode (' ', $array);

$dtemisformat = ''.$dtemisformat.'.000';

The code above returns me 2016-09-09 08:10:52.000 but the -03: 00 value in the $res1 = explode("-03:00", $res[1]); line is not always the same for example: -02: 00 .

Are there any suggestions for improving the code?

    
asked by anonymous 09.09.2016 / 15:10

2 answers

5

This date format is ISO8601 = "Y-m-d\TH:i:sO"; so you do not need to use explode or / e implode , use a class DateTime that will solve your problem:

$date = DateTime::createFromFormat( 'Y-m-d\TH:i:sO' , '2016-09-09T08:10:52-03:00' );

and after that you can format it efficiently like this:

echo $date->format('Y-m-d H:i:s');

As you are ignoring the last part I see no need to put 000 .

    
09.09.2016 / 15:21
5

It is simpler to leave this task with a specialized function / class. This formatted date is known as W3C , to pick up part of the date use the class DateTime and method format()

$d = DateTime::createFromFormat(DateTime::W3C, '2016-09-09T08:10:52-03:00');
echo $d->format('H:i:s');
    
09.09.2016 / 15:21