Cody Raspien
Cody Raspien

Reputation: 1845

Separate Date and Time from concatenated timestamp variable - PHP

I am calling an API. The format for timestamp returned is as follows:

"Date":"2018-05-06T23:42:03+01:00"

How do I separate date from time?

So far, what I have is:

$ts = "2018-05-06T23:42:03+01:00";
$date = substr($ts, 0, strpos($ts, "T"));
$date = str_replace($date,"T","");

While this would work, is there a better way of doing this?

Upvotes: 0

Views: 61

Answers (2)

zerkms
zerkms

Reputation: 254975

It would be a bad practice to use string functions over a properly formatted RFC3339 datetime.

Instead one would use a datetime parsing functions

$dt = \DateTime::createFromFormat(\DateTime::RFC3339, '2018-05-06T23:42:03+01:00');

var_dump($dt->format('H:i:s'));

Online demo: https://3v4l.org/uNGfG

References:

Upvotes: 2

surge10
surge10

Reputation: 642

Split them please

$ts = "2018-05-06T23:42:03+01:00";
$splits = explode('T', $ts);
$date = $splits[0]

Upvotes: 0

Related Questions