Search code examples
phpdatetimeiso8601

ISO8601 Date in PHP with Format YYYY-MM-DDTHH:MM:SS.mmmmmmmZ


I am trying to generate a timestamp in PHP for use with an API. I cannot seem to get the timestamp to format as it should. The proper format is:

UTC ISO8601 DateTime format: YYYY-MM-DDTHH:MM:SS.mmmmmmmZ

Example: 2013-04-24T11:11:50.2829708Z

Edit, Let me clarify on the actual issue I am having:

The 'Z' Property is returning the timezone offset in seconds. I need the offset returned as date('c') returns it.

Example: +01:00 instead of 3600

Is there a built in function for this in PHP?


Solution

  • You are looking for the DateTime::format method in combination with the c formatter or the DateTime::ISO8601 constant:

    $timestamp = new DateTime();
    echo $timestamp->format('c'); // Returns ISO8601 in proper format
    echo $timestamp->format(DateTime::ISO8601); // Works the same since const ISO8601 = "Y-m-d\TH:i:sO"