PHP Function of the Day (2011-9-16): date

[fphp]date[/fphp] has to be one of the most complicated functions in the PHP library - I still find myself looking up it’s format string parameters. Still, it’s very powerful and useful.

If you are making lots of calls to this function consider defining your format strings as a constant. This way if the format string must change you don’t have to look up every call to date in the system - just the spot where the constant was defined.

One place where date gets used where it shouldn’t is to transform all the dates of a mysql return into something more human readable, in the middle of a for loop. It is easier both from a code legibility standpoint and from the standpoint of CPU cycles to let MySQL handle this with its date_format function.

Perhaps the single most common mistake with date is the Minute indicator in the date format string - i. m is used for month.

The biggest complement to the date() function is strtotime(). It has helped me alot in doing stuff like this:

$today = date("Ymd");
$yesterday = date("Ymd", strtotime("-1 day", strtotime($today)));

I generally agree with that, except that your display layer is now inextricably linked to your data layer, which might be fine as long as you did this with your eyes fully open.

You would not want to do that if for example your date was going to be formatted to accommodate users from different countries, one which displays dd/mm/yyyy and another that displays mm/dd/yyyy.

Agreed. Stylistically I relegate data formatting to the model and make moderate use of the functions in MySQL that help with this - CONCAT, CONCAT_WS, and so on. When I say formatting with regards to a view I mean style formatting.

You would not want to do that if for example your date was going to be formatted to accommodate users from different countries, one which displays dd/mm/yyyy and another that displays mm/dd/yyyy.

Good example, though I personally shy away from that particular shorthand for that reason. I was born on June 8th, not August 6th :smiley:
It’s easier to avoid the issue entirely with the three digit abbreviation of the month name: “Jan 4 2001” doesn’t take noticably more space than “1/4/2001” but it certainly isn’t ambiguous between sides of the Atlantic.

Off Topic:

For those wondering, British convention is dd/mm/yyyy, American and Candadian convetion is mm/dd/yyy