ISO 8601 date in PHP

Converting ISO 8601 date string in PHP

JavaScript Date Object explained how to convert ISO 8601 dates in Javascript. Thanks to Ryan Kennedy, we have a function to convert ISO 8601 dates in PHP.

This is how you can call the function:

$theDateFormattedMyWay = date("F j, Y", parse_datetime($ISO8601_formate_date]));

For other possible formats, please visit:

You need to then include the parse_datetime function in your code. Hopefully the next version of PHP will include this, or something similar

function parse_datetime($datetime) {
     $currentTime = time();
     $offset = date("Z", $currentTime);
     $matches = array();
     // Check to see if we're dealing with a UTC dateTime (ends in 'Z') 
     // or if there's an offset specified (ends in '[+-]hh:mm').
          $datetime, $matches) === 1) {
     	// Offset specified.
     	$dateString = $matches[1];
     	// Calculate the custom offset.
     	$customOffset = $matches[3] * 60 * 60;
     	$customOffset += $matches[4] * 60;
     	// Invert the custom offset as necessary.
	if($matches[2] == "+") {
     		$customOffset = -1 * $customOffset;
     	// Add the custom offset to the UTC offset to get the offset 
     	// from the local timezone.
     	$offset += $customOffset;
     else if(preg_match("/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})Z$/", 
           $datetime, $matches) === 1) {
     	// Using the UTC timezone.
     	$dateString = $matches[1];
     // Parse the date and time portion of the string.
     $datetimeArray = strptime($dateString, "%Y-%m-%dT%H:%M:%S%");
     // Generate the UNIX time. Note that this will be in the wrong timezone.
     $time = mktime($datetimeArray['tm_hour'], 
     		$datetimeArray['tm_mon'] + 1, 
		$datetimeArray['tm_mday'] , 
     		$datetimeArray['tm_year'] + 1900);
      // Return the calculated UNIX time from above along with the offset 
      // necessary to correct for the timezone specified.
      return $time + $offset;
This entry was posted in PHP, Web Development. Bookmark the permalink.

4 Responses to ISO 8601 date in PHP

  1. Bramus! says:

    Why not use PHP’s native strotime function?

    $theDateFormattedMyWay = date("F j, Y", strtotime($ISO8601_formate_date])); works like a charm (and no need for extra functions ;))

  2. Ivan says:

    You forgot to include function strptime(); Generates error on run. Can you post the function? thanks.

  3. Aeomer says:

    strptime() is a PHP 5 function that is only implemented on *nix platforms. Forget this function and use strtotime instead.

  4. pinguino says:


Leave a Reply

Your email address will not be published. Required fields are marked *