O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Date and Time Functions

PHP uses the standard Unix-style timestamp to work with dates. This is simply the number of seconds since January 1, 1970. You get the current timestamp using the time function, shown in Example 11-15.

Example 11-15. A simple echo of the timestamp

<?php
$timestamp= time();
echo $timestamp;
?>

This results in Figure 11-13.

A Unix timestamp

Figure 11-13. A Unix timestamp

1134511981

This is not exactly the most meaningful representation of the date and time. So instead, you can use the date function to translate the timestamp into a meaningful string. The date function takes a timestamp and a format string, as shown in Example 11-16.

Example 11-16. Making the date and time appear like we expect

<?php
$timestamp= time();
echo date("m/d/y G.i:s",$timestamp);
?>

This code returns the screen shown in Figure 11-14.

An easy-to-read date and time from the date function

Figure 11-14. An easy-to-read date and time from the date function

Dates and times can be displayed in a variety of formats; these will be discussed next.

Display Formats

Date and times are displayed in a variety of formats. In Example 11-16, we used a date format string of m/d/y G.i:s. Table 11-2 shows other possible components for those formats.

Table 11-2. Time-formatting values

Format

Meaning

Example value

a

am or pm

Am

A

AM or PM

AM

d

Day of the month

01

D

Day or the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required