A Required Date Field With Time — But Time Not Required

Do you need a required date field to have an optional time? I did and I was surprised to discover that Date and CCK Time didn’t support this.

The Search

Event date and timeI first thought that the Date field could do it.  I created a date field with granularity defined down to the minute.  But that meant that the hour and second were required in addition to the year, month and day.

What about leaving the date field with year, month and day granularity and then adding another date field just with minutes and seconds?  Can’t do that, the date field requires that year be included in the granularity.

What about the CCK Time module?  While I did manage to find a port for Drupal 6, there was no option to have the field blank.

As for the Date module, they are working on a solution.  The issue has been reported many times over the years and many of the issues are marked duplicate.  Alas, the only open issue I found was for the dev version for Drupal 7.

The Solution

The solution was quite simple. Create a CCK text field with the Select List widget. In the Allowed Values List, add the values below.

Note that the the value to the of the pipe is the stored value while value on the right is the display value. Because we want to be able to sort on this field, and not deal with the headache AM/PM would cause, we’re storying the 24-hour time and will use that for sorting.

I found that I needed the leading zero on the 24 hour times representing hours 6 through 9 for sorting reasons.

One more thing.  The code below starts at 6 AM.  I didn’t need the early morning hours, so you’ll need to add times for hours 0 through 5 if you want the full 24-hour cycle.

0600|6:00 AM
0615|6:15 AM
0630|6:30 AM
0645|6:45 AM
0700|7:00 AM
0715|7:15 AM
0730|7:30 AM
0745|7:45 AM
0800|8:00 AM
0815|8:15 AM
0830|8:30 AM
0845|8:45 AM
0900|9:00 AM
0915|9:15 AM
0930|9:30 AM
0945|9:45 AM
1000|10:00 AM
1015|10:15 AM
1030|10:30 AM
1045|10:45 AM
1100|11:00 AM
1115|11:15 AM
1130|11:30 AM
1145|11:45 AM
1200|12:00 PM
1215|12:15 PM
1230|12:30 PM
1245|12:45 PM
1300|1:00 PM
1315|1:15 PM
1330|1:30 PM
1345|1:45 PM
1400|2:00 PM
1415|2:15 PM
1430|2:30 PM
1445|2:45 PM
1500|3:00 PM
1515|3:15 PM
1530|3:30 PM
1545|3:45 PM
1600|4:00 PM
1615|4:15 PM
1630|4:30 PM
1645|4:45 PM
1700|5:00 PM
1715|5:15 PM
1730|5:30 PM
1745|5:45 PM
1800|6:00 PM
1815|6:15 PM
1830|6:30 PM
1845|6:45 PM
1900|7:00 PM
1915|7:15 PM
1930|7:30 PM
1945|7:45 PM
2000|8:00 PM
2015|8:15 PM
2030|8:30 PM
2045|8:45 PM
2100|9:00 PM
2115|9:15 PM
2130|9:30 PM
2145|9:45 PM
2200|10:00 PM
2215|10:15 PM
2230|10:30 PM
2245|10:45 PM
2300|11:00 PM
2315|11:15 PM
2330|11:30 PM
2345|11:45 PM