I am currently using 8.17 and here is my code:

      $form['field_dob'] = array(
          '#type' => 'date',
          '#title' => 'Enter Your Date of Birth',
          '#required' => TRUE,
          '#default_value' => array('month' => 9, 'day' => 6, 'year' => 1962),
          '#format' => 'm/d/Y',
          '#description' => t('i.e. 09/06/2016'),
      );

So as you can see by my example, I am defaulting to the date 9/6/1962. After clearing the cache, what appears in the date field as literally as "9 6 1962" without the "/" deliminator. The popup calendar also displays today's date (August 25, 2016).

How can I get the date element to:

1. Allow and display dates to m/d/Y
2. Set the popup calendar correctly?

Thanks,

dotmundo

Comments

dotmundo’s picture

I solved it with the following code

// Get the custom date format that was created in System Configuration
$date_format_entity = DateFormat::load('my_custom_format');

// Get the date pattern
$date_format = $date_format_entity->getPattern();

// Either default to the last inputted date or today's date
$date = $form_state->getValue('field_date') ? $form_state->getValue('field_date') : date($date_format);

$form['field_date'] = array (
        '#type' => 'date',
        '#title' => 'Enter Your Date of Birth',
        '#format' => 'm/d/Y',
        '#description' => t('i.e. 09/06/2016'),
        '#required' => TRUE
        '#default_value' => $date,
        '#date_date_format' => $date_format,  // or 'm/d/Y'
 );

So this was solved by looking at Datetime.php, which is in Drupal core. As you can see, '#date_date_format' is where you tell Drupal your preferred date pattern. The default is whatever HTML Date (html_date) is set to which I did not want to change but could have been solved that way. The code at the beginning guarantees that you use the format you want to have but is not necessary as you can choose to hard-code the format.

sunilsinghgaur’s picture

Used the same code but it didn't change the format. For me still showing the dd/mm/yyyy even after clearing the cache. Is there anything that you did to achieve the date format?