You are here

public static function TwigConvert::dateFromFormat in Twig Tools 8

Converts a datetime string between different date formats.

Parameters

string $value: A datetime string that matches the $from_format date format.

string $from_format: A PHP datetime format string.

string $to_format: A PHP datetime format string.

string|null $from_timezone: The timezone identifier the datetime should be converted from.

string|null $to_timezone: The timezone identifier the datetime should be converted to.

Return value

string The datetime formatted according to the specific data format.

File

src/TwigExtension/TwigConvert.php, line 129

Class

TwigConvert
Class TwigConvert.

Namespace

Drupal\twig_tools\TwigExtension

Code

public static function dateFromFormat($value, $from_format, $to_format, $from_timezone = NULL, $to_timezone = NULL) {

  // Since a Unix timestamp can be 0 or '0', we need additional
  // empty/falsy checks.
  if (empty($value) && $value !== '0' && $value !== 0) {
    return '';
  }

  // Create a datetime object from the specified format.
  $converted_date = $from_timezone ? \DateTime::createFromFormat($from_format, $value, new \DateTimeZone($from_timezone)) : \DateTime::createFromFormat($from_format, $value);

  // Convert datetime to other timezone if specified.
  if (isset($to_timezone)) {
    $converted_date = $converted_date
      ->setTimezone(new \DateTimeZone($to_timezone));
  }

  // Return the datetime formatted in the specified format.
  return $converted_date
    ->format($to_format);
}