簡體   English   中英

format_date()不使用時區

[英]format_date() not working with timezone

  • Drupal 7.8安裝
  • 站點時區在區域設置中設置為America / New_York
  • 我在頁面回調中有這段代碼
  • 多個服務器上出現問題

format_date()不會通過默認站點時區調整時區偏移量,甚至不會將時區字符串作為參數添加。

下面是代碼,代碼底部是輸出注釋掉的。 使用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
  */

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM