Quarter/year custom formatter (datetime)

Showing quarter and year instead of date.

This is for a datetime field in D7.

/**
* Implements hook_field_formatter_info().
*/
function MYMODULE_field_formatter_info() {
  return array(
    'FORMATTER_NAME' => array(
      'label' => t('Quarter'),
      'field types' => array('datetime'),
    ),
  );
}

/**
* Implements hook_field_formatter_view().
*/
function MYMODULE_field_formatter_view($obj_type, $object, $field, $instance, $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {
    case 'FORMATTER_NAME':
      foreach ($items as $delta => $item) {
        if ($item['value']) {
          $date = new DateObject($item['value']);
          $quarter = ceil(date_format_date($date, 'custom', 'n', $langcode = NULL)/3);
          $year = date_format_date($date, 'custom', 'Y', $langcode = NULL);
          $element[$delta] = array(
           '#markup' => t('Quarter @quarter, @year', array('@quarter' => $quarter, '@year' => $year)),
          );
        }
      }
    break;
  }
  return $element;
}

About

This is the company blog of
Drupal specialist Merge.nl

We are located in Breda (Netherlands) and build websites using Drupal. More about us.

Content on this blog is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Netherlands License.

Creative Commons License

Recent Comments

Social