I am trying to programmatically load a node and get its date time value. The default format is HTML5 date, long date. I load it and I get the field value with the following code.
dpm($record['nid_value']); $entity = \Drupal\node\Entity\Node::load($record['nid_value']); dpm($entity->get('field_date_range')->value);
The output is the following one.
740 2018-02-23T02:00:00 734 2018-02-23T00:00:00
Why is it stored as 2018-02-23T02:00:00 when the real date is Thursday - February 22, 2018 - 4:00pm to 5:00pm?
The field type is date range; the display type is smart range. When you view the node, it looks perfect. The display is correct. If I create a view, it also outputs the incorrect date, no matter what format I chose on the field output. Time zone has been forced.
Can anyone point me in the right direction here?
UPDATE - Here was the solution to my problem
$nid = 411; $entity = \Drupal\node\Entity\Node::load($nid); $dval = $entity->get('field_date_range')->value(); $dt = new DateTime($dval, new DateTimeZone('UTC')); $dt->setTimezone(new DateTimeZone('America/Los_Angeles')); $date_to_print = $dt->format('g:ia \o\n l jS F Y'); //$date_to_print = $dt->format('m-d-Y h:m:i'); echo $date_to_print; //output: 12:00pm on Saturday 24th February 2018