I use the following code to create a node.

    $datetime = "2016-08-01 12:30:00";
    $values = array(
      'title' => $data['title'],
      'body' => $data['body'],
      'field_client' => $uid,
      'field_appointment_date_time' => $datetime,
      'type' => 'appointment'

  $appointment = Node::create($values);

The problem is that field_appointment_date_time (a Datetime field) is not been saved.

Why does this happen?


The above code is correct, date time was saved into DB. the problem is frontend.

frontend expected this format:

"2016-08-01T12:30:00", need a "T" as separator.

here is how to put that T as separator,

\DateTime::format("Y-m-d\Th:i:s"), need a escape character in-front of T.

2016-01-22 update:

By the way, I have found out in Drupal 8 , correct way to store datetime is follow:

1> first , find out current user timezone, \Drupal::currentUser()->getTimezone()

2> $given = new \Drupal\Core\Datetime\DrupalDateTime("2016-08-01T12:30:00",$user->getTimezone());

3> $given->setTimezone(new \DateTimeZone("UTC"));

4> then get back formated datetime string $given->format("Y-m-d\Th:i:s");

I had the same problem, please try this

$dateTime = \DateTime::createFromFormat('Y-m-d','2000-01-30');
$newDateString = $dateTime->format('Y-m-d\TH:i:s');
$node = \Drupal\node\Entity\Node::create(array(
          'type' => 'article',
          'title' => 'The title',
          'langcode' => 'en',
          'uid' => 1,
          'status' => 1,
          'body' => array('The body text'),
          //'field_date' => array("2000-01-30"),
          'field_date' => $newDateString,

I've picked it from here:https://www.drupal8.ovh/en/tutoriels/64/create-a-node-date-field

I hope it helps you.

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.