Displaying the Date or Time in PHP

The simplest display of date or time is telling your users what time it is. For this, use the format() method of a DateTime object, as shown in Example 15-1.

Example 15-1. What time is it?

$d = new DateTime();

print ‘It is now: ‘;

print $d->format(‘r’);

print \n;

At noon on October 20, 2016, Example 15-1 would print:

It is now: Thu, 20 Oct 2016 12:00:00 +0000

When you create a DateTime object, the time or date to store inside it is provided to the object constructor. If no argument is provided, as in Example 15-1, the current date and time are used. The format string passed to the format() method controls how the date and time are formatted for printing.

Individual letters in the format string translate into certain time values. Example 15-2 prints out a month, day, and year.

Example 15-2. Printing a formatted date string

$d = new DateTime();

print $d->format(‘m/d/y’);

At noon on October 20, 2016, Example 15-2 would print:


In Example 15-2, the m becomes the month (10), the d becomes the day of the month (20), and the y becomes the two-digit year (04). Because the slash is not a format character that format() understands, it is left alone in the string that format() returns.

Table 15-1 lists all of the special characters that DateTime::format() understands.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *