# File: 12_hour_time_select.rb
# Created: July 16, 2006
# Author: Andrew Dorr at CubeSix Technologies Inc.
# Wiki: http://wiki.rubyonrails.org/rails/pages/12+hour+time+select
# Download: http://cubesix.net/rails/plugins/12_hour_time_select/
#
# Description:
# This is a simple plugin that overrides the default select_time method
# in order to provide support for a 12 hour clock. The 24 hour time
# functionality is fully retained.
#
# Use:
# Copy the 12_hour_time_select directory and its contents to your
# vendor/plugins/ directory
# In your view, add <%= select_time(datetime, :twelve_hour => true) %>
#
# For example, when creating a time object in your controller, do like so:
# @new_job.time = params[:date] + ' ' +
# params[:time][:hour] + ':' +
# params[:time][:minute] + ' ' +
# params[:time][:meridiem]
#
# Ruby will take care of the rest.
#
# Credits:
#
# Based on:
# flex_times by Sean Cribbs (http://wiki.rubyonrails.org/rails/pages/FlexTimes+Plugin)
# 12_hour_time by Nick M. (http://wiki.rubyonrails.com/rails/pages/12-Hour+Time+Plugin)
# Ruby on Rails DateHelper (http://api.rubyonrails.com/classes/ActionView/Helpers/DateHelper.html)
#
# Feel free to do what you will with this code, but credit me if you make
# changes and rerelease it.
module ActionView::Helpers::DateHelper
def select_time(datetime = Time.now, options = {})
if options[:twelve_hour]
h = select_hour(datetime, options) + select_minute(datetime, options) + select_meridiem(datetime, options) + (options[:include_seconds] ? select_second(datetime, options) : '')
else
h = select_hour(datetime, options) + select_minute(datetime, options) + (options[:include_seconds] ? select_second(datetime, options) : '')
end
end
def select_hour(datetime, options = {})
hour_options = []
if options[:twelve_hour]
first_hour, last_hour = 1, 12
hr_format = "%I"
else
first_hour, last_hour = 0, 23
hr_format = "%H"
end
first_hour.upto(last_hour) do |hour|
time = Time.local(0, 1, 1, ((datetime.kind_of?(Fixnum)) ? datetime : datetime.hour))
selected = (time.strftime("%H").to_i == hour) ? ' selected="selected"' : ''
hour_options << %(\n)
end
select_html(options[:field_name] || 'hour', hour_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
end
def select_meridiem(datetime, options={})
meridiem_options = []
["AM", "PM"].each do |value|
time = Time.local(0, 1, 1, ((datetime.kind_of?(Fixnum)) ? datetime : datetime.hour))
selected = (time.strftime("%p") == value) ? ' selected="selected"' : ''
meridiem_options << %(\n)
end
select_html(options[:field_name] || 'meridiem', meridiem_options, options[:prefix], options[:include_blank], options[:discard_type], options[:disabled])
end
end