Format dates the drupal way use core function and date api (with timezones and adjustable formats)

Posted by: 
Dominique De Cooman

The main function in drupal to format a date is the format_date function which will take the formatting and timezone conversion you configured at http://yoursite/admin/settings/date-time and http://yoursite/admin/settings/date-time/formats

<?php
//format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)
//An example convert the unix timestamp for now 
format_date(time(), 'medium''''Europe/Brussels');
?>

For more : http://api.drupal.org/api/function/format_date/6

When working with http://drupal.org/project/date and you have something like this stored into the database:

2010-06-11T14:00:00

You ll need to convert the stored format to a unix timestamp

<?php
//date_convert($date, $from_type, $to_type, $tz = 'UTC')
$timestamp date_convert($node->field_date[0]['value'], DATE_ISODATE_UNIX);
format_date($timestamp);

//When you try to do this you will NOT have the correct timestamp, it will not not take into account the timezone. So following is wrong
$timestamp strtotime($node->field_date[0]['value']);
?>

More on formats in the date.api.inc file or date_convert function.

Why is this all important? When moving code from one server to another located in different timezones the times displayed on your site not using the correct formatting functions may change. This may not seem to have a big impact when your just displaying dates. But when logic depends on it, let us say you only can register for this test until date x, it can cause the page to be in accesible too soon or too late.

Add new comment