Convert a date field to the correct time zone

Public

When you are working with the raw value of a date field, you need to convert it from the database time zone to the user's time zone. Otherwise, a date entered as "1 Januari 2013" may be rendered as "31 December 2012". This is my preferred method.

Get raw version
php
  1. // Example: Assume we have a node with nid 1 which contains a single
  2. // language-neutral date field named field_date.
  3. $node = node_load(1);
  4. $date = $node->field_date[LANGUAGE_NONE][0];
  5.  
  6. // Create a date object.
  7. $date_object = new DateObject($date['value'], new DateTimeZone($date['timezone_db']));
  8. // Convert from the database time zone to the user's time zone.
  9. $date_object->setTimezone(new DateTimeZone($date['timezone']));
  10.  
  11. // Example: Print a formatted date.
  12. print date_format_date($date_object, 'custom', 'Y m d');

Comments

Samir's picture

Thanks!