Format value with explode and implode PHP

Asked

Viewed 382 times

4

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

To return me 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 to me 2016-09-09 08:10:52.000 however the value -03:00 on the line $res1 = explode("-03:00", $res[1]); various, not always being the same for example: -02:00.

Is there any suggestion to improve the code ?

  • What is the purpose of this code, just the time?

  • The date and time is after that I give an input in the database. So I need to format.

2 answers

5

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

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

5


This date format is ISO8601 = "Y-m-d\TH:i:sO"; so you don’t have to use explode or/and implode, use the datetime class 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 efficiently so:

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

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

  • I understood, I had forgotten DateTime.

  • 1

    No hassle @Kevin. F, the important thing is it gives a better user experience and helping is always good.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.