Convert DateTime to String in PHP
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.
|
1 2 3 4 5 6 7 |
<?php $date = new DateTime("2017/10/25 18:30:10"); $str = $date->format("Y/m/d H:i:s"); var_dump($str); // string(19) "2017/10/25 18:30:10" ?> |
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.
|
1 2 3 4 5 6 7 |
<?php $date = date_create("2017/10/25 18:30:10"); $str = date_format($date, "Y/m/d H:i:s"); var_dump($str); // string(19) "2017/10/25 18:30:10" ?> |
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".
|
1 2 3 4 5 6 7 |
<?php $date = new DateTime("2017/10/25 18:30:10"); $str = $date->format(DateTimeInterface::RFC1036); var_dump($str); // string(29) "Wed, 25 Oct 17 18:30:10 +0200" ?> |
Finally, returning the current date and time in some specific format can be as simple as:
|
1 2 3 4 5 6 7 |
<?php $date = new DateTime(); $str = $date->format("Y/m/d H:i:s"); var_dump($str); // string(19) "2017/10/17 08:57:46" ?> |
That’s all about converting a DateTime object to a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)