Problem

Trying to create a DrupalDateTime object from timestamp : 1634590800 (2021-10-18 23:00:00 for my timezone).
The datetime objects returns 0800-10-18 16:34:59.0 Europe/Paris (+00:09)
This should work with timestamp according to the PHP Doc of

DrupalDateTime::__construct() method

.

=> It's working when the timestamp is converted to a datetime before :

$date = date('Y-m-d H:i:s', $timestamp);
$datetme = new Drupal\Core\Datetime\DrupalDateTime\DrupalDateTime($date);

Steps to reproduce

$date = new Drupal\Core\Datetime\DrupalDateTime\DrupalDateTime($timestamp);

Proposed resolution

Use

Drupal\Component\Datetime\DateTimePlus::prepareFormat

by default to match the PHP Doc?

Comments

Pauline G created an issue. See original summary.

cilefen’s picture

Component: base system » datetime.module
Issue tags: -datetime
murilohp’s picture

Assigned: Unassigned » murilohp

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.1.10 (June 4, 2021) and Drupal 9.2.10 (November 24, 2021) were the last bugfix releases of those minor version series. Drupal 9 bug reports should be targeted for the 9.3.x-dev branch from now on, and new development or disruptive changes should be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

murilohp’s picture

Hey @pauline-g sorry for my delay for this response, I've assigned this to me and took a while to work on that, but I was able to reproduce this issue, and your idea solved the problem for me. The class DateTimePlus has the method prepareTime, and on it's doc says:

/**
   * Prepares the input time value.
   *
   * Changes the input value before trying to use it, if necessary.
   * Can be overridden to handle special cases.
   *
   * @param mixed $time
   *   An input value, which could be a timestamp, a string,
   *   or an array of date parts.
   *
   * @return mixed
   *   The massaged time.
   */
  protected function prepareTime($time) {

But the function is not preparing the string when it's a timestamp. So following your suggestion, the patch will validate and convert the $time to a readable date.

This problem was actually being caused by the function date_parse, used to convert date inside the __constructor, and this function only accepts date/time accepted by the DateTimeImmutable::__construct()., and timestamp is not valid for this scenario.

It would be nice to have more opinions regarding this scenario.

Thanks!

murilohp’s picture

Assigned: murilohp » Unassigned
Status: Active » Needs review
mfb’s picture

Status: Needs review » Closed (works as designed)

The documentation states

the $time parameter either is a UNIX timestamp (e.g. @946684800)

i.e. you need to prepend the numeric timestamp with '@':

echo new \Drupal\Core\Datetime\DrupalDateTime('@' . 1634590800);

which gives you 2021-10-18 21:00:00 +00:00