Bruno Miranda's Notebook

Personal Blog about Ruby on Rails, XHTML, CSS, and Design

As most of us already know, if you use the built in time_select helper to interface with a time column in your DB, your HTML select box will display military format. Most of us in the USA are not accustomed to telling time in this format.

After trying a couple of the rails plug-ins out there only to find out none of them worked, I consulted my buddy Rich who wrote a brilliantly simple date helper module to get the job done.

The code follows below:

module ActionView
  module Helpers
    module DateHelper
      def select_hour_with_twelve_hour_time(datetime, options = {})        
        return select_hour_without_twelve_hour_time(datetime, options) 
        unless options[:twelve_hour].eql? true

        val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) : ''
        if options[:use_hidden]
          hidden_html(options[:field_name] || 'hour', val, options)
        else
          hour_options = []
          0.upto(23) do |hour|
            ampm = hour <= 11 ? ' AM' : ' PM'
            ampm_hour = hour == 12 ? 12 : (hour / 12 == 1 ? hour % 12 : hour)

            hour_options << ((val == hour) ?
              %(\n) :
              %(\n)
            )
          end
          select_html(options[:field_name] || 'hour', hour_options, options)
        end
      end
      alias_method_chain :select_hour, :twelve_hour_time
    end
  end
end

Subversion Source:

http://svn.devjavu.com/bopia/twelve_hour/

Usage:

<%= time_select 'event', 'time', {:twelve_hour => true} %>

Trac:

http://bopia.devjavu.com/projects/bopia/report/1

The above will output something that looks like this:

Time: :

I’ve been looking for a way to limit the number of options under minute on timeselect and datetimeselect. You can set the :minute_step to 15 which will give you: 00, 15, 30 and 45.

<%= datetime_select 'game', 'game_date_time', {:minute_step => 15} %>

Hope that helps!