Printing DateTimes
suggest changePHP 4+ supplies a method, format that converts a DateTime object into a string with a desired format. According to PHP Manual, this is the object oriented function:
public string DateTime::format ( string $format )
The function date() takes one parameters - a format, which is a string
Format
The format is a string, and uses single characters to define the format:
- Y: four digit representation of the year (eg: 2016)
- y: two digit representation of the year (eg: 16)
- m: month, as a number (01 to 12)
- M: month, as three letters (Jan, Feb, Mar, etc)
- j: day of the month, with no leading zeroes (1 to 31)
- D: day of the week, as three letters (Mon, Tue, Wed, etc)
- h: hour (12-hour format) (01 to 12)
- H: hour (24-hour format) (00 to 23)
- A: either AM or PM
- i: minute, with leading zeroes (00 to 59)
- s: second, with leading zeroes (00 to 59)
- The complete list can be found here
Usage
These characters can be used in various combinations to display times in virtually any format. Here are some examples:
$date = new DateTime('2000-05-26T13:30:20'); /* Friday, May 26, 2000 at 1:30:20 PM */
$date->format("H:i");
/* Returns 13:30 */
$date->format("H i s");
/* Returns 13 30 20 */
$date->format("h:i:s A");
/* Returns 01:30:20 PM */
$date->format("j/m/Y");
/* Returns 26/05/2000 */
$date->format("D, M j 'y - h:i A");
/* Returns Fri, May 26 '00 - 01:30 PM */
Procedural
The procedural format is similar:
Object-Oriented
$date->format($format)
Procedural Equivalent
date_format($date, $format)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents