Formatting Date Time Entity Fields While Taking Daylight Saving Time (DST) Into Account In Drupal 8

Charlotte Bone
Charlotte’s Digital Web
1 min readOct 7, 2019

When you create a date time field in Drupal 8, it stores the date in UTC format and takes into account daylight saving time (DST) too. This means that if you have a field that has a date that is after the switch to DST and the current date is before the switch, it will display the time an hour out if you haven’t formatted the date correctly.

You might see a lot of examples out there that show you using the standard PHP date functions and pulling the raw value from the date field, however this does not work and will display the time an hour out even if you set the timezone. The best way, is to pull the DrupalDateTime object from the field. You can then get the timezone using drupal_get_user_timezone, set it on the field and then format the timezone and it will show the correct time.

The example below shows how you would do this for an entity field named field_start_date

$date = $entity->field_start_date->date;
$timezone = timezone_open(drupal_get_user_timezone());
$date->setTimeZone($timezone);
$date->format("D d M Y H:i");

--

--

Charlotte Bone
Charlotte’s Digital Web

I am a creative, passionate, full stack developer. I love technology & I really want more females to not be afraid to pursue this career / Engineer @stacker.app