Search code examples
phpdatedatetimeutc

How to convert yyyy-MM-dd HH:mm:ss to yyyy-MM-ddTHH:mm:ssZ?


I need to send the datetime to an API.

I am trying to do like this, but it isn't working.

$startDate = DateTime::createFromFormat('yyyy-MM-dd\THH:mm:ssZ', '2014-06-13 14:30:00');

Unfortunately I get 2014-06-13T13:30:00.000Z whereas I need it to be in this format: yyyy-MM-ddTHH:mm:ssZ

I'm not sure where I am going wrong. Any help or advice would be appreciated!


Solution

  • You're trying to convert and read in the date at the same time which is not how DateTime::createFromFormat() works. In fact, you don't need that method at all since your starting date format is supported by DateTime.

    Just pass the date as a parameter to DateTime() and then format it accordingly. (As noted in the comments, make sure your date is in UTC).

    echo (new DateTime('2014-06-13 14:30:00'))->format('Y-m-d\TH:i:s\Z');