Don't print the year on a date field if the date is in the current year

Public

If you have a place where you have a lot of dates showing that are in the current year, it might make sense to not show the year to decrease clutter and increase readability. For example, I have an academic calendar printed in a table for the current academic year, so I'd like to reduce clutter. Past or future years will still be printed. Date prints the full ISO date into an HTML attribute, so your date is still machine readable.

Get raw version
php
  1. /**
  2.  * Implements hook_date_formatter_dates_alter().
  3.  */
  4. function mymodule_date_formatter_dates_alter(&$dates, $context) {
  5. static $this_year;
  6. if (!isset($this_year)) {
  7. $this_year = date(', Y');
  8. }
  9.  
  10. // In this example, I am only applying this change to all instances of a specific date field.
  11. if ($context['field']['field_name'] == 'field_academic_date') {
  12. foreach ($dates as &$date) {
  13. $date['formatted'] = str_replace($this_year, '', $date['formatted']);
  14. }
  15. }
  16. }