I decided to write this short PHP tutorial on how to print a Date Time object because this is one of the frequent questions I get from people who are new with the language. Trying to print or echo a DateTime object the regular way you’d have done a variable or trying to loop through it thinking of it as an array object would not work. To get it printed out, you’d have to go a different route.
In order to display the date from a Date Time Object in PHP, you do not have to use the echo statement, as it would not return the date from the object. You have to make use of the date-format method ( date_format(); ) and below is the syntax of this method/function.
Date Format Syntax
[pastacode lang=”php” manual=”date_format(object%2Cformat)%3B” message=”php date format syntax” highlight=”” provider=”manual”/]
As can be seen, this method accepts two arguments. The first one being the object (date time object) to be printed and the second refers to the format it would be display.
The DateTime object could be a date saved and queried from say a MySQL Database (must have been created using the date_create() method), while the format argument accepts formatting strings that determines how the date and time would be displayed. Take the below code as an example.
[pastacode lang=”php” manual=”echo%20date_format(%24date%2C%22Y%20-%20m%20-%20d%20H%3Ai%3As%22)%3B” message=”Echo a php date_time object” highlight=”” provider=”manual”/]
Code Explanation
$date – Refers to the dateTime object created or queried from a DB.
Y – Refers to the year
m – Refers to the month
d – Refers to the day
H – Refers to the hour
i – Refers to the minute
s – Refers to the second.
Thus if the time/date pulled or created earlier was for the 3rd of January 2017 by 8:22 am, with the above formatting, the date time would be printed thus
2017 – 11 – 03 08:22:00
There are a lot of ways you might want to format your date time object and here is a list of other characters that can be used for formatting.
Note that the two arguments or parameters as you might call it are required in the Date Format method.
2 Comments
Very good. Thanks a lot Oscar.
Please I would like to interview you on my blog. Hope you don’t mind?
Hi Prince,
Thanks for dropping by. Sure I don’t mind. 🙂 . You can reach me via the contact page.