![]() |
VOOZH | about |
Converting a `DateTime` to a string in PHP involves formatting the `DateTime` object into a human-readable format using the `format()` method. This process allows you to represent dates and times as strings in various formats, such as Y-m-d H:i:s.
There are some following approaches
Table of Content
Example:
Output:
07/05/2021 17:57:38
Output:
05/07/2021 05:58:48The date_format() function provides an alternative way to format a DateTime object into a string. It is functionally similar to the format method of the DateTime class.
Example: In this example, the date_format() function takes a DateTime object and a format string as parameters. It formats the DateTime object into a string according to the specified format and returns the result.
05/07/2021 17:57:38 2021-07-05 17:57:38
The date() function in PHP can be used to format a timestamp into a human-readable string. By using the getTimestamp() method of the DateTime object, you can get the Unix timestamp and then format it with the date() function.
Example: This method offers an alternative way to format a DateTime object to a string, utilizing the date() function and the Unix timestamp provided by the getTimestamp() method.
05/07/2021 17:57:38
The strftime() function in PHP formats a local time/date according to locale settings. This function is particularly useful for producing date and time strings in a locale-aware manner.
Example: The following example demonstrates how to use the strftime() function to convert a DateTime object to a string.
07/05/2021 17:57:38
The IntlDateFormatter class provides a way to format dates and times according to locale-specific patterns. This can be particularly useful for internationalization.
Example: This example demonstrates how to use the IntlDateFormatter class to convert a DateTime object to a string.
Output
05/07/2021 17:57:38The DateTimeImmutable class works similarly to the DateTime class but ensures that the date and time values cannot be modified after the object is created. This can be useful when you want to ensure the immutability of your date and time objects. You can still format the DateTimeImmutable object into a string using the format() method.
Example: The following example demonstrates how to use the DateTimeImmutable class to convert a date and time to a string.
05/07/2021 17:57:38