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
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.
$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.