13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Calculating Dates in <strong>PHP</strong><br />

477<br />

Table 21.4<br />

Continued<br />

%e Day of month, numeric, no leading zeros<br />

%m Month, numeric, leading zeros<br />

%c Month, numeric, no leading zeros<br />

%b Month, text, three characters<br />

%j Day of year, numeric<br />

%H Hour, 24-hour clock, leading zeros<br />

%k Hour, 24-hour clock, no leading zeros<br />

%h or %I Hour, 12-hour clock, leading zeros<br />

%l Hour, 12-hour clock, no leading zeros<br />

%i Minutes, numeric, leading zeros<br />

%r Time, 12-hour (hh:mm:ss [AM|PM])<br />

%T Time, 24-hour (hh:mm:ss)<br />

%S or %s Seconds, numeric, leading zeros<br />

%p AM or PM<br />

%w Day of the week, numeric, from 0 (Sunday) to 6 (Saturday)<br />

The UNIX_TIMESTAMP function works similarly but converts a column into a Unix timestamp.<br />

For example,<br />

SELECT UNIX_TIMESTAMP(date_column)<br />

FROM tablename;<br />

returns the date formatted as a Unix timestamp.You can then do as you want with it in<br />

<strong>PHP</strong>.<br />

You can easily perform date calculations <strong>and</strong> comparisons with the Unix timestamp.<br />

Bear in mind, however, that a timestamp can usually represent dates only between 1902<br />

<strong>and</strong> 2038, whereas the <strong>MySQL</strong> date type has a much wider range.<br />

As a rule of thumb, use a Unix timestamp for date calculations <strong>and</strong> the st<strong>and</strong>ard date<br />

format when you are just storing or showing dates.<br />

Calculating Dates in <strong>PHP</strong><br />

A simple way to work out the length of time between two dates in <strong>PHP</strong> is to use the<br />

difference between Unix timestamps.We use this approach in the script shown in Listing<br />

21.1.<br />

Listing 21.1 calc_age.php—Working Out a Person’s Age Based on Birthdate<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!