HighlyStructured.com is a blog website run by Mike D'Agostino about search engine positioning, online marketing, php/MySQL, tae kwon do, and various other topics.

PHP Date Function Quick Reference

March 17, 2006

In a previous post, I talked about comparing dates in PHP and some techniques you may be able to use. I thought I would follow up on that post with a general guide to storing, retrieving, and working with dates in PHP.

I think the best way to store dates in a MySQL database when using PHP is not to store them as MySQL defined dates, but rather as varchars. The varchar will actually be a Unix Timestamp. The benefit is that a date in a Unix Timestamp is literally a count of of the number of seconds since the epoch - January 1 1970 00:00:00 GMT. If you need to compare dates, it makes it as easy as seeing which number is higher or lower.

Suppose, for instance, you are recording in your database the date someone registers for your website. All you need to do is simply create a variable to hold the date in the Unix Timestamp format. The code might look like:

$date_signup = date("U");

"date" is a common PHP function and "U" tells PHP that you would like the date to be formatted in the Unix Timestamp format.

Let's say though, that you have data that allows the date to be specified in a certain format, for example YYYY-MM-DD. In this case you would want to use the strtotime function:

$date = "2006-01-16";
$final_date = strtotime($date);

First you save your entered date into a variable, and then convert it to Unix Timestamp using strtotime.

Now you have your dates stored in your database. The next logical step would be to retrieve the dates, and either present them in some kind of formatted version, or compare them. If you want to simply display a date, it would be meaningless just presenting the Unix Timestamp. However you can use the PHP date function to format dates the way you choose. The syntax would look like this (assuming you've retrieved the date and assigned it to a variable "$date"):

$converted_date = date ("F d, Y", $date);

This will convert the date to something like "March 25, 2006". The "F d, Y" tell PHP how you'd like the date displayed. You can use pretty much any combination of number or letter formats for the month, day, and year. Take a look at PHP.net's date formatting guide for all the options.

And, if you want to compare dates, they are already in Unix Timestamp format and it is simply a matter of finding which value is higher or lower:

if ($end_date > $date) {
     $valid = "yes";
} else {
     $expired = "yes";
} //end if

There you have it! This should give you a nice guide to refer to when doing some basic stuff with PHP and dates.

Technorati Tags:       

Recent Articles

Topics

Archive

Other Blogs of Interest