You are here

class FormatDate in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/migrate/src/Plugin/migrate/process/FormatDate.php \Drupal\migrate\Plugin\migrate\process\FormatDate
  2. 9 core/modules/migrate/src/Plugin/migrate/process/FormatDate.php \Drupal\migrate\Plugin\migrate\process\FormatDate

Converts date/datetime from one format to another.

Available configuration keys

Configuration keys from_timezone and to_timezone are both optional. Possible input variants:

  • Both from_timezone and to_timezone are empty. Date will not be converted and be treated as date in default timezone.
  • Only from_timezone is set. Date will be converted from timezone specified in from_timezone key to the default timezone.
  • Only to_timezone is set. Date will be converted from the default timezone to the timezone specified in to_timezone key.
  • Both from_timezone and to_timezone are set. Date will be converted from timezone specified in from_timezone key to the timezone specified in to_timezone key.

Examples:

Example usage for date only fields (DateTimeItemInterface::DATE_STORAGE_FORMAT):


process:
  field_date:
    plugin: format_date
    from_format: 'm/d/Y'
    to_format: 'Y-m-d'
    source: event_date

If the source value was '01/05/1955' the transformed value would be 1955-01-05.

Example usage for datetime fields (DateTimeItemInterface::DATETIME_STORAGE_FORMAT):


process:
  field_time:
    plugin: format_date
    from_format: 'm/d/Y H:i:s'
    to_format: 'Y-m-d\TH:i:s'
    source: event_time

If the source value was '01/05/1955 10:43:22' the transformed value would be 1955-01-05T10:43:22.

Example usage for datetime fields with a timezone and settings:


process:
  field_time:
    plugin: format_date
    from_format: 'Y-m-d\TH:i:sO'
    to_format: 'Y-m-d\TH:i:s'
    from_timezone: 'America/Managua'
    to_timezone: 'UTC'
    settings:
      validate_format: false
    source: event_time

If the source value was '2004-12-19T10:19:42-0600' the transformed value would be 2004-12-19T10:19:42. Set validate_format to false if your source value is '0000-00-00 00:00:00'.

Plugin annotation


@MigrateProcessPlugin(
  id = "format_date"
)

Hierarchy

Expanded class hierarchy of FormatDate

See also

\DateTime::createFromFormat()

\Drupal\Component\Datetime\DateTimePlus::__construct()

\Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface

\Drupal\migrate\Plugin\MigrateProcessInterface

1 file declares its use of FormatDate
FormatDateTest.php in core/modules/migrate/tests/src/Unit/process/FormatDateTest.php

File

core/modules/migrate/src/Plugin/migrate/process/FormatDate.php, line 93

Namespace

Drupal\migrate\Plugin\migrate\process
View source
class FormatDate extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    if (empty($value) && $value !== '0' && $value !== 0) {
      return '';
    }

    // Validate the configuration.
    if (empty($this->configuration['from_format'])) {
      throw new MigrateException('Format date plugin is missing from_format configuration.');
    }
    if (empty($this->configuration['to_format'])) {
      throw new MigrateException('Format date plugin is missing to_format configuration.');
    }
    $fromFormat = $this->configuration['from_format'];
    $toFormat = $this->configuration['to_format'];
    $system_timezone = date_default_timezone_get();
    $default_timezone = !empty($system_timezone) ? $system_timezone : 'UTC';
    $from_timezone = $this->configuration['from_timezone'] ?? $default_timezone;
    $to_timezone = $this->configuration['to_timezone'] ?? $default_timezone;
    $settings = $this->configuration['settings'] ?? [];

    // Older versions of Drupal where omitting certain granularity values (also
    // known as "collected date attributes") resulted in invalid timestamps
    // getting stored.
    if ($fromFormat === 'Y-m-d\\TH:i:s') {
      $value = str_replace([
        '-00-00T',
        '-00T',
      ], [
        '-01-01T',
        '-01T',
      ], $value);
    }

    // Attempts to transform the supplied date using the defined input format.
    // DateTimePlus::createFromFormat can throw exceptions, so we need to
    // explicitly check for problems.
    try {
      $transformed = DateTimePlus::createFromFormat($fromFormat, $value, $from_timezone, $settings)
        ->format($toFormat, [
        'timezone' => $to_timezone,
      ]);
    } catch (\InvalidArgumentException $e) {
      throw new MigrateException(sprintf("Format date plugin could not transform '%s' using the format '%s'. Error: %s", $value, $fromFormat, $e
        ->getMessage()), $e
        ->getCode(), $e);
    } catch (\UnexpectedValueException $e) {
      throw new MigrateException(sprintf("Format date plugin could not transform '%s' using the format '%s'. Error: %s", $value, $fromFormat, $e
        ->getMessage()), $e
        ->getCode(), $e);
    }
    return $transformed;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormatDate::transform public function Performs the associated process. Overrides ProcessPluginBase::transform
MessengerTrait::$messenger protected property The messenger. 18
MessengerTrait::messenger public function Gets the messenger. 18
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition.
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function
PluginBase::getDerivativeId public function
PluginBase::getPluginDefinition public function 2
PluginBase::getPluginId public function
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 53
ProcessPluginBase::multiple public function Indicates whether the returned value requires multiple handling. Overrides MigrateProcessInterface::multiple 3
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 1
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.