13.09.2016 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

479<br />

An option that may not seem immediately obvious is using <strong>MySQL</strong>. <strong>MySQL</strong> provides<br />

an extensive range of date manipulation functions that work for times outside the<br />

reliable range of Unix timestamps.You need to connect to a <strong>MySQL</strong> server to run a<br />

<strong>MySQL</strong> query, but you do not have to use data from the database.<br />

The following query adds one day to the date February 28, 1700, <strong>and</strong> returns the<br />

resulting date:<br />

select adddate(‘1700-02-28’, interval 1 day)<br />

The year 1700 is not a leap year, so the result is 1700-03-01.<br />

You can find an extensive syntax for describing <strong>and</strong> modifying dates <strong>and</strong> times<br />

described in the <strong>MySQL</strong> manual; it is located at http://www.mysql.com/doc/en/<br />

Date_<strong>and</strong>_time_functions.html.<br />

Unfortunately, there is not a simple way to get the number of years between two<br />

dates, so the birthday example is still a little flaky.You can get a person’s age in days very<br />

easily, <strong>and</strong> Listing 21.2 converts that age to years imprecisely.<br />

Listing 21.2 mysql_calc_age.php—Using <strong>MySQL</strong> to Work Out a Person’s Age<br />

Based on Birthdate<br />

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

Saved successfully!

Ooh no, something went wrong!