1

I have an Event content type with a Date field with a start and end date.

enter image description here

When this field is being displayed in a view, it displays properly, with the time matching the value that was entered.

enter image description here

On a different page, I am overriding field--field-date.tpl.php and using date_create and date_format to print out the date and time separately.

$start_date = date_create($node->field_date['und'][0]['value']); //dont hate me
$end_date = date_create($node->field_date['und'][0]['value2']);
//...
print date_format($start_date, 'g:i A') . ' - ' . date_format($end_date, 'g:i A'); 

enter image description here

As you can see, it is displaying 4:00pm instead of 12:00pm. It looks like a timezone translation is happening (or not happening) somewhere. I tried to screw around with the time zone argument for date_create but nothing actually changed the way the date displayed.

When I dump the date field out with devel, I get,

dpm($node->field_date['und'][0]['value']);
dpm($start_date);

enter image description here

How do I actually display the proper timezone for my date with PHP in my field--field-date.tpl.php?

1 Answer 1

1

Looks like your date field is configured to use either site zone or user time zone configuration.

So, while saving the node drupal expects the entered value in usertime zone or site time zone and then convert it to UTC before saving it to database.

While showing it views consider the timezone configuration and format the date as per current user viewing the date field.

The timezone you see as 'America/NewYork' in the dpm result is the timezone configuration of the user created the node.

In order to show the date with format you can use format_date, something like below.

$user_time_zone = drupal_get_user_timezone();
format_date(strtotime($node->field_date['und'][0]['value']), 'custom', 'm/d/Y h:i:sA', $timezone = $user_time_zone);

Important thing is to choose the right configuration for your field timezone settings, if the date field is irrespective to current user timezone keep the timezone configuration to UTC.

1
  • Note that format_date is depricated now.
    – Bram
    Feb 14, 2018 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.