How to Convert DateTime to String in PHP
Table of Contents
You can represent an exact date and time in PHP using the built-in DateTime object.
Creating one is simple, just pass it a string in the format YYYY-MM-DD HH:MM:SS
.
The problem is that sometimes you want to go from a DateTime object back to a string.
In this post, we'll learn how to convert a DateTime object to a string in PHP.
How to convert a DateTime object to a string
To start, let's create our own DateTime object.
PHP$date = new DateTime('2020-01-01 00:00:00');
The easiest way to convert this back to a readable string is to call the format
method on it and pass it the format in which you want to get the string in.
PHP$date = new DateTime('2020-01-01 00:00:00');
$results = $date->format('Y-m-d H:i:s');
echo($results);
BASH2020-01-01 00:00:00
The useful part about format
is that if the format fails because the DateTime object or the format you passed in is invalid, it will return false
.
Because of this, you can use this check to ensure the formatting was succesful:
PHP$date = new DateTime('2020-01-01 00:00:00');
$results = $date->format('Y-m-d H:i:s');
if ($results) {
echo($results);
} else {
echo('Formatting failed');
}
BASH2020-01-01 00:00:00
Conclusion
In this post, we learned how to convert a DateTime object to a string.
Simply call the format
method on your DateTime object and pass the method the date format you want your DateTime formatted to.
Thanks for reading and happy coding!
- Getting Started with Solid
- Getting Started with Express
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React