Create a node With date field | Drupal 8

Create a node With date field

Submitted by editor on Fri, 12/04/2015 - 16:22
Question

How to create and format a date field.

It is same as normal node creation but must be in format "Y-m-d" (YYYY-MM-DD)

Example:

$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,
    ));
$node->save();

Comments

Roman Bensman (not verified)

Tue, 11/29/2016 - 02:11

DATETIME_DATETIME_STORAGE_FORMAT, which is 'Y-m-d\TH:i:s'

                  $dateTime = \DateTime::createFromFormat('Y-m-d','2000-01-30');
                  $newDateString = $dateTime->format('Y-m-d\TH:i:s');

                  and

            'field_date' => $newDateString,

https://www.drupal.org/node/2795353

Thanks it works for me, but I would like to know why Drupal adds one hour more to the time I added programatically.

Say I had the following:

$dateTime = \DateTime::createFromFormat('Y-m-d H:i:s','2000-01-30 12:00:00');
$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' => $newDateString,
    ));
$node->save();

The above code is supposed to store something like 2000-01-30 12:00:00 in the database, but what I actually get is 2000-01-30 13:00:00.

Please note the difference 12:00:00 and 13:00:00

 

Thanks

 

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.