PHP DateTime Create From Format (‘c’) Error

Category: Tips
Last modified on February 5, 2025

Introduction

PHP provides a convenient API for working with date and time. If you need to retrieve the current date, you can simply use the date() function, specifying the desired format as an argument. Alternatively, in WordPress, you can use the wp_date() function, which applies the site’s current time zone to the date.

In programming, the ISO 8601 format is often used to store technical date-related information. PHP has a specific format character for this purpose: c.

For example, using date('c') will return a string like this:

echo date( 'c' ); // Output: 2025-02-04T18:43:38+00:00

The Problem

However, there is an issue with this format, which might be a bug in PHP itself. The static method DateTime::createFromFormat() allows you to create a DateTime object from a string that matches a specified format. But if you try to create a DateTime object using the c format, the result will not be a DateTime object but false.

$date = date( 'c' ); $datetime = DateTime::createFromFormat( 'c', $date ); print_r( gettype( $datetime ) ); // Prints 'boolean', value – false.

The exact reason for this behavior remains unclear.

The Solution

As of now, there is only one workaround for this issue: explicitly specify the date and time format that corresponds to ISO 8601, which is Y-m-d\TH:i:sP

$date = date( 'c' ); $datetime = DateTime::createFromFormat( 'Y-m-d\TH:i:sP', $date ); print_r( gettype( $datetime ) ); // Prints 'object'.

Related Posts

by the same categories