Browse By

PHP Date Tips & Tricks

For those of you using PHP to develop your web pages, I’m sure that you have used the date function at some point. There are so many cases that I have used this to show a date on a page, like using date(“Y”) in the copyright section of the footer to always reflect the current year. Here are a few tips & tricks to help you save some time.

Formatting

Predefined Constants

This is a trick that I really wish I had known about earlier. PHP 5.1.1 and forward offers date formatting constants. So when I was looking for examples on how to get the date in the correct format when creating my RSS feed, I could have simply used the DATE_RSS constant.

Example

Use:

<? echo date(DATE_RSS); ?>
Output: Thu, 24 Nov 2008 12:29:09 -0500

Instead of:

<? echo date('D, d M Y G:i:s O'); ?>
Output: Thu, 24 Nov 2008 12:29:09 -0500

There are eleven total predefined constants available including DATE_RSS, DATE_ATOM, DATE_COOKIE, and DATE_W3C.

User Defined Constants

Building on this same idea of constants, you could easily create your own date format constants to use. All you would need to do is define a constant with the string value of the date format and then call it within the date function. I have included a simple example below.

Example

<? define(DATE_SCOTT,'m/d/Y'); ?>
<? echo date(DATE_SCOTT); ?>
Output: 11/24/2008

Relative Dates

This trick is one I use when I need to get a date like tomorrow or the day after tomorrow or yesterday. The function strtotime allows you to easily calculate dates like tomorrow and yesterday. You can turn any GNU formatted date string into a PHP date. I have included a couplt of examples below that are based on a publish date of 11-24-2008.

Example

<? echo date('m-d-Y',strtotime('yesterday')); ?>
Output: 11-23-2008

<? echo date('m-d-Y',strtotime('+4 days')); ?>
Output: 11-28-2008

Calculate Age

This trick is a fairly simple and straight forward one. All it does is find an age in years. Simply pass the year(s) you want to compare and it will return the age in year. This could easily be made into a function like getAge($yr1,$yr2);

<? echo floor(abs(strtotime('Y') - strtotime('1985'))/31536000
/*1 year in seconds*/); ?>
Output: 23


4 thoughts on “PHP Date Tips & Tricks”

  1. Pingback: PHP Date Tips & Tricks | PHP-Blog.com
  2. Trackback: PHP Date Tips & Tricks | PHP-Blog.com
  3. Pingback: Consejos para trabajar con fechas en PHP. | webmasters, recursos webmasters, recursos gratuitos, scripts, web
  4. Trackback: Consejos para trabajar con fechas en PHP. | webmasters, recursos webmasters, recursos gratuitos, scripts, web
  5. Mattias Geniar says:

    You can also replace the first one:
    date(DATE_RSS);

    with the RFC 2822 compliant version:
    date(“r”);

    Which will output the same date (ie: “Thu, 21 Dec 2000 16:01:07 +0200”)

Comments are closed.

%d bloggers like this: