Separating month or time from year in an exposed filter

If you have ever tried to create an exposed filter for a view using Drupal's Views module you may have noticed when creating an exposed filter on a date field that you can not filter on months or days individually, this can be a problem if your client requests such a feature as there are no configuration settings in Views to achieve this.

A workaround which worked for me and was very fast and easy to set up was as follows: 

Create a computed field on the content type(s) in question using Computed Field module, you then add some PHP into this computed field which converts the value of the date field into a month integer value. Now in your view rather than filtering on the date field, you filter on this computed field.

Step 1. Install Computed Field module.

Step 2. Create a new computed field on your content type and name it something appropriate like "Month Computed"

Step 3. In the field settings for the computed field in the Computed Code (PHP) section enter the following code. Replacing "field_date" with the machine name of your date field. You can find the machine name by going to the Manage Fields section of your content type.

$field = field_get_items($entity_type, $entity, "field_date");
$date = $field[0]['value'];
$month = date("m",strtotime($date));
$entity_field[0]['value'] = "$month";

What this code does is to use a Drupal function called field_get_items to grab the fields data, we then need to simply grab the actual date value from the field data, and this is what is happening on line 2. The 3rd line converts the date into a month integer value, and the 4th line assigns this value to the computed field.


Step 4. You may need to bulk save all your content for the content type in question since this computed field does not get calculated until a node is saved. Luckily there is a module to achieve this in bulk called Resave Nodes.

Step 5. Now go back to your view and add a new field in the filter section which is your computed field, make the filter exposed for this field and make it a grouped filter.

Step 6. Now it is a case of assigning each Month to the correct value, bare in mind that the value in the computed field is numerical i.e. January = 01, February = 02 and so on. You can see a screenshot below of what this looks like.

views screenshot

Save your view and you should now be able to filter on Month without having to pick a year to go with it... Great success!