Format_date () does not work with timezone

  • Install Drupal 7.8
  • The time zone of the site is set to America / New_York in the region settings.
  • I have this code in a page callback
  • The problem occurs on multiple servers.

format_date () does not adjust the timezone offset either clockwise the default site, or even when I add a timezone line as an argument.

Below is the code, and at the bottom of the code is the output comment. There are 2 examples using format_date, and the last example is what I had to do in order to get the right time to display.

Any ideas on how to get format_date () to work 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", "Ymd h:s:i"): '. format_date($timestamp, 'custom', 'Ymd 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", "Ymd h:s:i", "America/NewYork"): '. format_date($timestamp, 'custom', 'Ymd 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('Ymd h:s:i', ($timestamp + $offset)); print $formatted; /** This is the output format_date($timestamp, "custom", "Ymd h:s:i"): 2011-09-01 02:00:00 format_date($timestamp, "custom", "Ymd h:s:i", "America/NewYork"): 2011-09-01 02:00:00 2011-09-01 10:00:00 */ 
+4
source share
1 answer

The way you solved it is true. If you are using PHP 5.3 or higher, you can use the DateTime :: add method and simply add the offset without creating a timestamp, as 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('Ymd H:i:s', $dateTime->format('U') + $offset); 
+3
source

All Articles