Skip to content

Instantly share code, notes, and snippets.

@rdetert
Last active December 18, 2015 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rdetert/5834265 to your computer and use it in GitHub Desktop.
Save rdetert/5834265 to your computer and use it in GitHub Desktop.
Uses Pikaday and Moment JS jQuery plugins to make a user-friendly DateTime picker to work with Rails
<%= stylesheet_link_tag "pikaday", :media => "all" %>
<%= form_for(@news) do |f| %>
<!-- Generate HTML -->
<%= form_datetime_selector_helper(:obj => f,
:field_name => :publish_date,
:label_name => 'Publish Date',
:date => @news.publish_date).html_safe %>
<% end %>
<%= javascript_include_tag "moment.js" %>
<%= javascript_include_tag "pikaday.js" %>
<%= javascript_include_tag "pikaday.jquery.js" %>
<script>
var startpicker = new Pikaday({
field: $('#news_publish_date_date')[0],
format: 'MMM D, YYYY'
});
$("#news_publish_date_date, #news_publish_date_hour, #news_publish_date_minute, #news_publish_date_ampm").change(function(){
var d = $("#news_publish_date_date").val();
var h = $("#news_publish_date_hour").val();
var m = $("#news_publish_date_minute").val();
var ampm = $("#news_publish_date_ampm").val();
$("#news_publish_date").val(d + ' ' + h + ':' + m + ampm); // populate the hidden field to submit back to server
});
</script>
def form_datetime_selector_helper(args = {})
f = args[:obj]
field_name = args[:field_name].to_sym
full_fieldname = "#{f.object_name}_#{field_name}"
date = args[:date]
formatted_date = date.strftime("%b %-d, %Y") unless date.nil? # => MMM D, YYYY
@hour_options = {"hour" => ""}
(1..12).each do |hour|
@hour_options = @hour_options.merge({ hour.to_s => hour })
end
@minute_options = {"minute" => ""}
['00', '15', '30', '45'].each do |minute|
@minute_options = @minute_options.merge({ minute.to_s => minute })
end
@ampm_options = {"select" => ""}
['am', 'pm'].each do |ampm|
@ampm_options = @ampm_options.merge({ ampm.to_s => ampm })
end
hour = date.try(:hour)
if hour
hour -=12 if hour > 12
end
minute = date.try(:minute)
if minute
minute = "00" if minute.to_i == 0
end
date_field = <<-FIELDS
<div class='datetime'>
<div>
#{f.label field_name, args[:label_name], :class => 'datetime-label'}
#{f.hidden_field field_name, :class => 'datetime-hidden'}
</div>
<div style="float:left">
#{text_field_tag "#{full_fieldname}_date", formatted_date, :size => 10 }
</div>
<div style="float:left">
#{select_tag "#{full_fieldname}_hour", options_for_select(@hour_options.to_a, hour) }
</div>
<div style="float:left">
#{select_tag "#{full_fieldname}_minute", options_for_select(@minute_options, minute) }
</div>
<div style="float:left">
#{select_tag "#{full_fieldname}_ampm", options_for_select(@ampm_options, date.try(:strftime, "%P")) }
</div>
<div style="clear:both"></div>
</div>
FIELDS
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment