This article demonstrates how to convert a DateTime object to a string in PHP.

You can use the format() function of the DateTime class to convert a DateTime object to string in PHP. The DateTime::format function returns the date formatted according to the given format.

Download  Run Code

 
Alternatively, you can use the date_format() function to get the formatted date according to the given format. Note that date_format() is an alias of the DateTime::format() function.

Download  Run Code

 
There are some predefined constants defined in the DateTimeInterface interface that can be used with the format() function:


ATOM = Y-m-d\\TH:i:sP
COOKIE = l, d-M-Y H:i:s T
ISO8601 = Y-m-d\\TH:i:sO
ISO8601_EXPANDED = X-m-d\\TH:i:sP
RFC822 = D, d M y H:i:s O
RFC850 = l, d-M-y H:i:s T
RFC1036 = D, d M y H:i:s O
RFC1123 = D, d M Y H:i:s O
RFC7231 = D, d M Y H:i:s \\G\\M\\T
RFC2822 = D, d M Y H:i:s O
RFC3339 = Y-m-d\\TH:i:sP
RFC3339_EXTENDED = Y-m-d\\TH:i:s.vP
RSS = D, d M Y H:i:s O
W3C = Y-m-d\\TH:i:sP

 
To demonstrate, the following solution uses DateTimeInterface::RFC1036 constant, which corresponds to the RFC 1036 pattern "D, d M y H:i:s O".

Download  Run Code

 
Finally, returning the current date and time in some specific format can be as simple as:

Download  Run Code

That’s all about converting a DateTime object to a string in PHP.