0

I made a date range field, and after entering some values and saving on first glance it looks ok, if i entered 20:00:00h it will display the same, but in the DB when i look at the stored values it's -2h (so 18:00:00). Anyone know why?

Also this is a huge problem when manually retrieving the values from the node, i fiddled around the time zones etc but i always get the value stored in the DB.

$node = Node::load($node_id);
$date = $node->get('field_date_ept2')->getValue()[0];
$result = \Drupal::service('date.formatter')->format($date['value'], 'custom', 'Y-m-d\TH:i:s', 'Europe/Berlin);
echo $result; // 2019-12-12T18:00:00

p.s. the timezone in my drupal 8 site is "Europe/Berlin" and the same as in my php.ini file.

1

The datetime value stored in DB is the UTC value. Any built in date formatter should give you the correct local time on the page. However if you need to manually get it from DB you'll have to convert the timezone yourself.

1

All dates are stored in UTC timezone. So your drupal account has a timezone set which is +2hours from UTC and drupal is converting that back to UTC before storing the date.

Here's how you can get the timezone back into the correct format in code. Elsewhere in views and stuff it should happen automatically:

$start_date = $v->field_MY_FIELD->start_date;
\Drupal::service('date.formatter')->format($start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s');

That will return it in whatever the current user/default site timezone is set as. Or you can specify the timezone:

\Drupal::service('date.formatter')->format($start_date->getTimestamp(), 'custom', 'Y-m-d H:i:s', 'Europe/London');
  • I did exactly that and I still get the wrong time, i will update my question with my code. – lordZ3d Apr 17 at 8:43
  • Can you do a dump of what your $date['value'] value actually is before you try it in the formatter? – Leigh Apr 17 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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