Managing timezones in Drupal 7
I especially don't want to forget this one myself.
When entering a time in a Drupal datetime field, datetimes are saved in one particular timezone in the database (mostly UTC). When programmatically loading and printing the time, you want to display it in the correct timzone (probably the website's or user's timezone).
This is how it's done:
Line 17 and 18 is where the magic happens.
"But Drupal has its own date_format() function which includes a timezone parameter?", you say. That's true and it will help us in the solution above. The key is all about what parameter 1 of this function is containing (in our example $date_converted). It has to be a UNIX timestamp which already contains timezone information, and that's what we're doing on line 18.
When entering a time in a Drupal datetime field, datetimes are saved in one particular timezone in the database (mostly UTC). When programmatically loading and printing the time, you want to display it in the correct timzone (probably the website's or user's timezone).
This is how it's done:
Line 17 and 18 is where the magic happens.
/** * Format the UTC time to our current timezone. * * @param string $date * Format: [Y-m-d H:i:s]. * @param string $timezone * Defaults to default Drupal timezone. * * @return string $output * Return the datetime in format [Y-m-d H:i:s]. */ function format_date_timezone($date, $timezone = NULL) { if (isset($date)) { if (!$timezone) { $timezone = date_default_timezone(FALSE); } $timezone_db = 'UTC'; $date_converted = strtotime($date . ' ' . $timezone_db); $output = format_date($date_converted, 'custom', 'Y-m-d H:i:s', $timezone); return $output; } return FALSE; }
"But Drupal has its own date_format() function which includes a timezone parameter?", you say. That's true and it will help us in the solution above. The key is all about what parameter 1 of this function is containing (in our example $date_converted). It has to be a UNIX timestamp which already contains timezone information, and that's what we're doing on line 18.
Add new comment