Format date using "date.formatter" service
"date.formatter" provides format
method for date-time formatting which accepts the following parameters.
- Timestamp - Unix timestamp
- Type - Date time format, default or defined in drupa backend, Use "custom" to provide custom format.
- Format - PHP date format, works if type is set to "custom"
- Timezone - Timezone
- Langcode - Language code for translation
\Drupal::service('date.formatter')->format($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL);
Example 1 -
$date = new DrupalDateTime('now');
$date_string = \Drupal::service('date.formatter')->format(
$date->getTimestamp(),
'medium'
);
Example 2 -
$date = new DrupalDateTime('now');
$date_string = \Drupal::service('date.formatter')->format(
$date->getTimestamp(),
'custom',
'd/m/Y'
);
Format date using DrupalDateTime
class.
DrupalDateTime
class extends DateTimePlus
class of Drupal DateTime component and provides different methods to create, format, and render a date
Example 1 -
$date = new DrupalDateTime('2022-11-18 00:00:00', 'UTC');
$date->setTimezone(new \DateTimeZone('America/Chicago'));
$date_string = $date->format('m/d/Y g:i a');
Example 2 -
// Get unix timestamp
$timestamp = $node->field_date->date->getTimestamp();
// Get a formatted date
$date_formatted = $node->field_date->date->format('Y-m-d H:i:s');
Date formatting in Twig template.
We have date
and format_date
filters to use with twig in Drupal.
Example 1-
{# Convert timestamp to a defined format. #}
{{ node.field_date.value|date('U')|format_date('medium') }}
{# Convert to custom format. #}
{{ node.field_date.value|date('Y-m-d') }}