0

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?

Cody Raspien
  • 1,753
  • 5
  • 26
  • 51
  • What exact problem are you solving? Given it's a properly formatted RFC3339 why do you want to treat it as strings? – zerkms May 06 '18 at 23:08
  • Yeah - separate them so I can store them in a table - 1 attribute for time another for date - makes my queries faster if I only rely on date. – Cody Raspien May 06 '18 at 23:09
  • You're not following me: why do you treat it as a string while you can treat it as a proper instant? https://3v4l.org/uNGfG – zerkms May 06 '18 at 23:10
  • Related, but not a duplicate: [RFC 3339 how make a dateTime from](https://stackoverflow.com/q/21383088/2943403) – mickmackusa May 06 '18 at 23:35

2 Answers2

2

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:

zerkms
  • 249,484
  • 69
  • 436
  • 539
0

Split them please

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