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

//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 :

When working with and you have something like this stored into the database:


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

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

//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 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

Who are you?

By knowing who you are you will be directed to a page where we have displayed all our drupal services relevant to your professional identity.