4

The default date format used by Drupal 8 is d.m.Y. I want to change it to d-M-Y.

I tried the following code, but it doesn't change the date format.

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start date'),
  '#format' => 'd-m-Y',
];

Even when I replaced #format with #date_format, the date was still using the default format.

What is the correct property to use for the date format, if #format and #date_format aren't recognized?

1 Answer 1

14

In Drupal 8, the properties for the date format and the time format are two different and separated properties: #date_date_format sets the date format, while #date_time_format sets the time format, as in the following code.

$date_format = 'Y-m-d';
$time_format = 'H:i';
    
$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start date'),
  '#date_date_format' => $date_format,
  '#date_time_format' => $time_format,
];

Unfortunately, when HTML5 form elements are used for a datetime form element, the date and time formats must be one of the HTML5 formats. This is described in the documentation for Datetime::processDatetime(), which contains the following text.

#date_date_format: A date format string that describes the format that should be displayed to the end user for the date. When using HTML5 elements the format MUST use the appropriate HTML5 format for that element, no other format will work. See the DateFormatterInterface::format() function for a list of the possible formats and HTML5 standards for the HTML5 requirements. Defaults to the right HTML5 format for the chosen element if a HTML5 element is used, otherwise defaults to DateFormat::load('html_date')->getPattern().

#date_time_format: A date format string that describes the format that should be displayed to the end user for the time. When using HTML5 elements the format MUST use the appropriate HTML5 format for that element, no other format will work. See the DateFormatterInterface::format() function for a list of the possible formats and HTML5 standards for the HTML5 requirements. Defaults to the right HTML5 format for the chosen element if a HTML5 element is used, otherwise defaults to DateFormat::load('html_time')->getPattern().

As Christian pointed out in his comment, there is an issue that (as of today, December 3, 2021) is currently open: Datetime element formats are confusing.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.