2

I've been looking around for a little while for what I thought would be a simple question to answer but I cannot seem to find the answer.

The question is: How can I convert a date with the format 2017-05-27 into a Drupal safe format for saving into the database?

I have looked inside Drupal\datetime\DateTimeComputed but I'm not sure that is the right place. Any help would be appreciated.

3
  • Okay! Looks like I found exactly what I was looking for. For anyone else looking around for the same or similar thing, check out the link below. That's where I found my answer. Why is my Datetime field not saved? May 27 '17 at 21:00
  • I think the linked question is for a different kind of date field.
    – 4k4
    May 27 '17 at 21:13
  • Hey! @4k4, thanks for that. Your answer is more accurate. Much appreciated. May 27 '17 at 21:38
4

The node created field is a Timestamp Field. Use the php function strtotime() to convert the string to a Unix timestamp:

$timestamp = strtotime('2017-05-27');

and store the value in the created field:

$node->created->value = $timestamp;

You can also use the method setCreatedTime():

$node->setCreatedTime($timestamp);

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.