Date element: Improper checks on strtotime outcome

Created on 14 February 2023, about 2 years ago

Problem/Motivation

When trying to format the date 1970/01/01, formatting fails.

Steps to reproduce

Create a webform with a date field and submit it with the value 1970/01/01.
Somewhere, use a token with formatting: [webform_submission:values:date:d-m-Y].

When using drush php:

$webform_submission = \Drupal\webform\Entity\WebformSubmission::load(1);
echo \Drupal::token()->replace('[webform_submission:values:date:d-m-Y]', compact('webform_submission'));

The result will be the value as it was saved in the database and not the expected 01-01-1970.

Proposed resolution

There are 2 problems in src/Plugin/WebformElement/DateBase.php.

The first problem is the usage of empty() in the method formatTextItem on line 193:

$timestamp = strtotime($value); # strtotime('1970/01/01') -> 0
if (empty($timestamp)) {        # empty(0) -> true
  return $value;
}

This check should be done with:

$timestamp = strtotime($value);
if ($timestamp === FALSE) {
  return $value;
}

The second problem is the improper check on $timestamp in the method formatDate on line 709:

protected static function formatDate($custom_format, $timestamp = NULL) {
  /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
  $date_formatter = \Drupal::service('date.formatter');
  return $date_formatter->format($timestamp ?: \Drupal::time()->getRequestTime(), 'custom', $custom_format);
}

Because $timestamp = 0 and the usage of ?:, this method will format the current request timestamp instead of the given $timestamp.
This can be fixed by using the null coalescing operator:

protected static function formatDate($custom_format, $timestamp = NULL) {
  /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
  $date_formatter = \Drupal::service('date.formatter');
  return $date_formatter->format($timestamp ?? \Drupal::time()->getRequestTime(), 'custom', $custom_format);
}

Attached is a patch file which includes my suggestions as described above.

πŸ› Bug report
Status

Fixed

Version

6.1

Component

Code

Created by

πŸ‡³πŸ‡±Netherlands sanderwind Friesland

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024