All I want to do is get the value out of a date field in Drupal 8, but they have done an expert job of making this impossible. The error I get is that 'dateTimeObject' is protected so I have no access to it.

enter image description here

  • 1
    You are talking about fields, but are showing a form snippet? Which are you having problems with? If you are using a form, can you show your $form element? If you are using a entity/field, is it datetime or daterange? – mpdonadio Jan 17 '17 at 15:03
  • 1
    Also, if I am reading that debug screen properly, it looks like you are in a form_after, and have grabbed the field element already which appears to be a \Drupal\Core\Datetime\DrupalDateTime object already. This has a public interface (and essentially wraps a \DateTime object and inherits its methods via magic methods, which isn't documented terribly well). You need to explain a bit better what you are trying to accomplish and what problems you are having. – mpdonadio Jan 17 '17 at 23:41
  • To add to what @mpdonadio said, since you are talking about code, you should show it. Users should not guess what code you are using, where you are using it, and what error you could have done in writing it. – kiamlaluno Jan 20 '17 at 17:41

Try this out -

$schedule_start = $form_state->getValue('field_start')->format("Y-m-d H:i:s");
$schedule_end = $form_state->getValue('field_end')->format("Y-m-d H:i:s");

Provide your own desirable format.

  • 1
    This will work, but it would be better to get the timestamp from the DrupalDateTime() object and then pass this to the date.formatter service instead of using the DrupalDateTime::format() method. – mpdonadio Jan 17 '17 at 23:01

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