format_date () не работает с часовым поясом - PullRequest
4 голосов
/ 17 октября 2011
  • Drupal 7.8 установить
  • Часовой пояс сайта установлен в Америка / Нью-Йорк в настройках региона
  • У меня есть этот код на странице обратного вызова
  • Проблема возникает на нескольких серверах

format_date () не корректирует смещение часового пояса ни по часовому поясу сайта по умолчанию, ни даже когда я добавляю строку часового пояса в качестве аргумента.

Ниже приведен код, а внизу кода - закомментированный вывод. Существует 2 примера использования format_date, и последний пример - это то, что мне нужно было сделать, чтобы получить правильное время для отображения.

Есть идеи, как заставить format_date () работать с часовым поясом?

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

1 Ответ

3 голосов
/ 22 марта 2012

То, как вы решили это правильно. Если вы используете PHP 5.3 или выше, вы можете использовать метод DateTime :: add и просто добавить смещение, не делая из него временную метку, как я делал ниже.

$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);
...