3

I'd like to format my date select input, using the following time formats:

  • 12-hour format of an hour without leading zeros
  • Minutes with leading zeros

Here's my form definition:

  $form['scheduled_for'] = array(
    '#type' => 'date_select',
    '#title' => t('Scheduled for'),
    '#date_label_position' => 'within',
    '#date_format' => 'd-F-Y g:i',
    '#date_increment' => 15,
    '#date_year_range' => '-0:+3',
    '#default_value' => time(),
  );

However, the hours format as 24-hour format of an hour without leading zeros (code G).

It's as if 'g' is being turned into 'G'. Any ideas? Thanks.

4
+50

In date_parts_element() there's the line

$hours_format  = strpos(strtolower($element['#date_format']), 'a') ? 'g': 'G';

This is deciding on whether to be 24 hour on the presence of the AM/PM specifier. If you change the format to d-F-Y g:i a it should work I think.

If you don't want to display the AM/PM specifier, but fix it at a particular value, you can do something like this

  ...
  // Add a new process function to this date_select to hardcode am/pm.
  $info = element_info('date_select');
  $process = $info['#process'];
  $process[]= 'MYMODULE_date_select_process_am_only';

  $form['scheduled_for'] = array(
    '#type' => 'date_select',
    '#title' => t('Scheduled for'),
    '#date_label_position' => 'within',
    '#date_format' => 'd-F-Y g:i a',
    '#date_increment' => 15,
    '#date_year_range' => '-0:+3',
    '#default_value' => time(),
    '#process' => $process,
  );
  ...

/**
 * #process callback for a date_select element that removes the AM/PM specifier
 * and hardcodes its value to AM.
 */
function MYMODULE_date_select_process_am_only($element) {
  $element['ampm']['#type'] = 'value';
  $element['ampm']['#value'] = 'am';

  return $element;
}

It's untested but works in my head (: If you wanted to do the same thing on a number of different forms, there's a more elegant way (let me know if you're interested).

  • That does work. It adds an am/pm input box as well, which I wasn't intending to have because in the context of my use case the time will always be during the day time - 3am would never be relevant - but I can live with the extra input box. Thanks. – 24ma13wg Sep 5 '14 at 9:07
  • @24ma13wg I've added some details for removing the extra input box. – Andy Sep 5 '14 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.