Saturday, 24 February 2007

PHP: Dates in readable european format

Dates in PHP is a bit confusing at first. It uses the UNIX datestamp, which is the number Seconds since the UNIX epoch started, January 1, 1970. There are many opytions to transform dates but here I want to discuss the following.

When adding an entry in the database, I also add the date and time of that moment by using the NOW() statement in the SQL query that inserts the entry into the DB.

$sql = "INSERT INTO table_1 (entry_a, entry_b, entry_date)
VALUES ('$entry1', '$entry2', NOW())";

mysql_query($sql);

This inserts a date like below into the database:

2007-02-05 01:26:25

When displaying the date of an entry however I want to show only the date not the time, and show it in the European format which is day-month-year. To do this I use the following simple function:

function dateformat($date)
{
$datum = substr($date,8,2); //day
$datum = $datum . '-' . substr($date,5,2); //month

$datum = $datum . '-' . substr($date,0,4); //year

echo $datum;
}

To call this function I use:

echo 'entry date: ';
echo dateformat($date);
after I read the $date from the database.

This will show on the webpage as:

entry date: 05-02-2007

It's nothing fancy but it works and easy to understand. The function simply extracts parts of the date string from the specified position in the string with the specified length. For example:

$datum = substr($date,8,2);

Will extract a string of 2 characters starting at position 8 (the first character of the string is position zero). All the elements are added to the same string ($datum) with a dash in between them.

No comments: