How change date format on date field drupal 8

6.5k views Asked by At

I need help to change the date format on the date field on a specific date field as shown below from the default format which is dd/mm/yyy to d-m-Y

$form['availability']['check_in_date'] = array(
        '#type' => 'date',
        '#title' => $this->t('Check In Date'),
        '#date_date_format' => 'dd-mm-yy',
        '#required' => TRUE,
        '#description' => $this->t('Please enter your check in date'),
        '#default_value' => (isset($customer_data->check_in_date)) ? $customer_data->check_in_date : '',
        '#attributes' => array('data-drupal-date-format' => "dd-mm-yy", 'type'=> 'date', 'min'=> '-1 day', 'max' => '+12 months'),
    );

I have tried the recommended way of adding the date field to form as shown from this link

I even tried the suggestions below as part of the comment on the page event with this suggestion here

All seems not to work, any ideas. thanks.

2

There are 2 answers

0
afro-Nija On

Basically I have tried many things but not working so i have just created the field as textfield and added the javascript datepicker to achieve the same result without breaking the drupal process and I am able to achieve the result i wanted.

Based on this I assume it is a bug in drupal 8 until it is fixed and a better workaround is provided for developers to be able to specify the format they want.

0
Vinay Sreedhara On

This worked for me, by using hook_form_alter and changing the form field elements


$form["field_date_of_birth"]["widget"][0]['value']['#attributes']['data-drupal-date-format'] = ['d/m/Y'];
$form["field_date_of_birth"]["widget"][0]['value']['#date_date_format'] = 'd/m/Y';
$form["field_date_of_birth"]["widget"][0]['value']['#date_date_element'] = 'text';
$form["field_date_of_birth"]["widget"][0]['value']['#attributes']['title'] = t('Enter a valid date - e.g. @format', [
    '@format' => (new \DateTime())->format('d/m/Y'),
  ]);