Formatting Date with PHP

Using PHP , yo easily format the date as a string in a whole variety of ways. Let’s say for instance you extract the date from a row in a MySQL database. By default it may appear as ‘2010-01-15’. In this format it is not easy to read and not very attractive. The following PHP snippets will show you a few methods for formatting and adding current date values to a web page.

To keep things simple, let’s start by putting together a string with a date value in it.

<?php
$my_date = “2010-01-15”;
echo “My date without formatting is $my_date”;
?>

If the above was viewed in your browser (ensuring that your server runs PHP and that your file ends with ‘.php’), you should see the date as follows:

Example: My date without formatting is 2010-01-15

In the next example, rather than using a string to form the date, we will use the current server ‘timstamp’ via PHP’s ‘date()’ function. By default, this will show ‘Year-month-day’.

<?php
$now_date = date(“Y-m-d”);
echo “Today’s date  is $now_date”;
?>

Now, let’s format today’s date to using the date() function. The following will display the date as ‘day-month-year’.

<?php
$now_date = date(“d-m-Y”);
echo “Today’s date, in a friendlier format  is $now_date”;
?>

Example: Today’s date, in a friendlier format is 15-01-2010

Formatting a string date

Earlier, we looked at ‘my_date’ in the form of a string – so who do we format such data? Simple, we convert the string to a date using PHP’s strtotime() function, aka “String to time”.

<?php
$my_date = “2010-01-15”;
$my_date = date(“d/m/Y”,strtotime($my_date));
echo “My date with formatting is $my_date”;
?>

Example: My date with formatting is 15/01/2010

This will convert the string ‘$my_date’ into a proper timestamp and then format it using date().

Try out the following for something a little different:

<?php
$my_date = “2010-01-15”;
$my_date = date(“l jS of F Y”,strtotime($my_date));
echo “My date with formatting is $my_date”;
?>

Example: My date with formatting is Friday 15th of January 2010

Date formats to try

Here are a few formats to try out for yourself when using the date() function:

Day

  • d = 01-31
  • J = 1-31
  • D = Mon-Sun
  • l (lowercase ‘L’) = Monday-Sunday

Month

  • m = 01-12
  • n = 1-12
  • M = Jan-Dec
  • F = January-December

Year

  • Y – 2010
  • y = 10

 See also Formatting Strings with PHP.