【问题标题】:format_date() not working with timezoneformat_date() 不适用于时区
【发布时间】:2011-10-17 19:44:46
【问题描述】:
  • Drupal 7.8 安装
  • 在区域设置中将站点时区设置为 America/New_York
  • 我在页面回调中有这段代码
  • 问题发生在多台服务器上

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

【问题讨论】:

  • 阿格。首先,我认为 Drupal 文档是错误的,因为它表明当您选择“日期的时区”时,日期不会转换并且时区会被存储。它确实存储了时区,但它清楚地将日期转换为 UTC。如果要在模板中使用它,则必须使用一堆代码将其转换回偏移量。您的代码运行良好,但在 Drupal 中处理不正确。

标签: drupal drupal-7 drupal-modules


【解决方案1】:

你解决它的方式是正确的。如果您使用 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);

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多