5

I already asked a question like this (Set date field in D8).

Ok duplicate entry? NO!

Now i have also to set a time and i'm using a array. My code looks like this.

$field_array = [
##begin of creating node
'uid' => $new_old_uid["new_uid"],
'type' => $content_type,
'langcode' => $lang,
'status' => (!empty($import_node->status)) ? $import_node->status : 0,

#### How to create date with times?
#Every Version causes that error -> Array to string conversion in ....
### Version 1
'field_event_date_start' => [[ "value"=> date('Y-m-d H:i:00',$imported_date) ]],
'field_event_date_end' => [[ "value"=> date('Y-m-d H:i:00',$imported_date) ]],
### Version 2
'field_event_date_start' => [ "value"=> date('Y-m-d H:i:00',$imported_date) ],
'field_event_date_end' => [ "value"=> date('Y-m-d H:i:00',$imported_date) ],


### How to add a url?
'field_event_url' => (!empty($import_node->field_event_url)) ? array('value'=> $imported_url) : null,
];

UPDATE: Another try for datetime field:

'field_event_date_start' => array(
    "value" => array(
        "date" => date('Y-m-d',$imported_date),
        "time" => date('H:i:00',$imported_date)
    ),
),

Now I'm getting following error: Placeholders must have a trailing [] if they are to be expanded with an array of values.

11

Datetime fields in Drupal 8 are stored as strings. So you need to convert it into string.

You can use the format method, e.g.

$formatted_date = $date->format('Y-m-d H:i:s');

Refer Inserting the value from Datetime field form

You can also use T as separator,

Like:

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

Refer Why is my Datetime field not saved?

  • thx works like charm! – themca Sep 20 '16 at 7:14
2

If your date field is not a DATETIME but a DATE, use a different format. And a better solution would be to use the Datime object constant to get the format.

constant DATETIME_STORAGE_FORMAT :: string(12) "Y-m-d\TH:i:s"
constant DATE_STORAGE_FORMAT :: string(5) "Y-m-d"

Working example.

$dtime = DateTime::createFromFormat("m/d/Y - G:i", $row->Date); // not needed
$dtime->setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$dtimeFormat = $dtime->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);

$article->set('field_date', $dtimeFormat);
0

This works great for date fields, as noted. However, if you need to update a timestamp based field use something like:

 $entityref->set('field_timestamp_field', $source_date->getTimestamp());

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.