4
  • Drupal 7.8 install
  • Site Timezone set to America/New_York in the region settings
  • I have this code in a page callback
  • Problem happens on multiple servers

format_date() is not adjusting for the timezone offset by either the default site timezone, or even when I add the timezone string as an argument.

Below is the code, and at the bottom of the code is the output commented out. There are 2 examples using format_date, and the last example is what I had to do to get the correct time to display.

Any ideas on how to get format_date() working with the timezone?

  header('content-type: text/plain');

  // utc_str as it would come from the db of a date field
  $utc_str = '2011-09-01 14:00:00';
  // converting to a unix timestamp
  $timestamp = strtotime($utc_str);

  // first print with format_date, note default site timezone is America/New_York
  print 'format_date($timestamp, "custom", "Y-m-d h:s:i"): '. format_date($timestamp, 'custom', 'Y-m-d h:s:i') ."\n";

  // next print date by actually setting the timezone string in the argument
  // Result:
  $tz_str = 'America/New_York';
  print 'format_date($timestamp, "custom", "Y-m-d h:s:i", "America/NewYork"): '. format_date($timestamp, 'custom', 'Y-m-d h:s:i', $tz_str) ."\n";

  // this is the only way i could get it working
  $date = new DateTime($product->field_class_date['und'][0]['value'], new DateTimeZone(date_default_timezone_get()));
  $offset = $date->getOffset();
  $formatted = date('Y-m-d h:s:i', ($timestamp + $offset));
  print $formatted;

  /** This is the output

    format_date($timestamp, "custom", "Y-m-d h:s:i"): 2011-09-01 02:00:00
    format_date($timestamp, "custom", "Y-m-d h:s:i", "America/NewYork"): 2011-09-01 02:00:00
    2011-09-01 10:00:00
  */
Coder1
  • 13,139
  • 15
  • 59
  • 89
  • Agggh. First off I think Drupal documentation is wrong as it indicates when you select "Date's time zone" the date is not converted and the timezone is stored. It does store the timezone but its clearly converting the date to UTC. Which you then have to convert back with an offset using a bunch of code if you want to use it in a template. Your code works great but this is not handled correctly in Drupal. – John81 Nov 05 '13 at 20:40

1 Answers1

3

The way you have solved it is correct. If you use PHP 5.3 or higher you can use the DateTime::add method and simply add the offset, without making a timestamp from it like i did below.

$utcTimezone = new DateTimeZone('UTC');
$timezone = new DateTimeZone('America/New_York');
$dateTime = new DateTime('2011-09-01 14:00:00', $timezone);
$offset = $timezone->getOffset($dateTime);
print date('Y-m-d H:i:s', $dateTime->format('U') + $offset);
DD dev
  • 166
  • 1
  • 7