From PHP version 5.2 onwards, the DateTime class has been available to create timestamp objects, providing developers with a convenient way to handle dates and times.
format methodWe can use the format method in order to represent the date as a string in a flexible format. Try the example below where we format a date in a couple of different styles.
<?php$myDate = new DateTime();echo $myDate->format('jS M Y');echo "\n";echo $myDate->format('d/m/y');?>
Let’s explain the code provided above.
Line 3: Set the $myDate variable to a new DateTime object.
Line 5: Print the $myDate variable using the formatting template jS M Y.
Line 8: Print the $myDate variable using the formatting template d/m/y.
The format method takes a string argument that specifies the desired date format. This format string utilizes letters to represent the different components of the date, including the day, week, month, and year. Additionally, symbols like colons (:), hyphens (-), and slashes (/) can be directly included in the output string to further customize the formatting.
Character | Meaning | Example |
| Number representing the day | 1, 31 |
| Number representing the day of the month, with a leading zero if applicable | 01, 31 |
| Combined to produce the English representation of the day of the month | 1st, 2nd |
| Number representing the month, with a leading zero if applicable | 01, 12 |
| Short text representation of the month with 3 characters | Jan, Feb |
| 2 digit representation of the year | 99, 23 |
| At least, 4 digit representation of the year | 1999, 2023 |
Let’s discuss the details of DateTime object from the above code snippet.
DateTime objectPHP DateTime objects implement an interface called DateTimeInterface. The DateTimeInterface specifies methods, including format method, that the DateTime class should implement. The DateTime class in PHP comes with pre-defined constant strings that represent date formats including the popular formats such as ATOM and ISO8601.
We can format a DateTime object by calling the format method and passing a format constant as the argument. Try running the example below, where we create a new DateTime object and then format it using the ATOM and ISO8601 constants.
<?php$myDate = new DateTime();echo $myDate->format(DateTimeInterface::ATOM);echo "\n";echo $myDate->format(DateTimeInterface::ISO8601);?>
Line 3: We set the $myDate variable to a new DateTime object.
Line 5: We print the $myDate variable using the ATOM format. The ATOM format formats the date in this format: Y-m-d\\TH:i:sP.
Line 8: We print the $myDate variable using the ISO8601 format. The ISO8601 formats the date in this format Y-m-d\\TH:i:sO.
Free Resources