Skip to content

Instantly share code, notes, and snippets.

@nacengineer
Last active December 18, 2015 01:49
Show Gist options
  • Save nacengineer/5706663 to your computer and use it in GitHub Desktop.
Save nacengineer/5706663 to your computer and use it in GitHub Desktop.
Twitter Bootstrap DateTimePicker w Ruby on Rails & Simple Form & Haml
# generally this will go in app/inputs/date_time_picker_input.rb and
# Simple Form will require it up automatically on initialization
class DateTimePickerInput < SimpleForm::Inputs::Base
def input
template.content_tag(:div, class: 'datetimepicker input-append') do
template.concat @builder.text_field(attribute_name, input_html_options) + span_div
end
end
def input_html_options
{'data-format' => "MM/dd/yyyy HH:mm PP"}
end
def span_div
template.content_tag(:span, class: 'add-on') do
template.concat icon_div.html_safe
end
end
def icon_div
"<i class='icon-calendar' data-time-icon='icon-time' data-date-icon='icon-calendar'></i>"
end
end
# this would go into your coffee file in app/javascripts
# and be required in your application.js, i.e. "//= require time"
# set minimum start date to now
$(document).ready ->
$('.datetimepicker').datetimepicker({
language: 'en',
pick12HourFormat: true,
startDate: new Date()
});
# in your view within the simple_form_for block
= f.input :js_start_time, as: :date_time_picker, label: "Start Time"
class YourObject < ActiceRecord::Base
attr_accessible :js_start_time
def time_format(time)
time.present? ? time.localtime.strftime("%m/%d/%Y %I:%M:%S %p") : time
end
def parse_us_time(time)
time_with_zone = "#{time} #{DateTime.now.strftime("%z")}"
DateTime.strptime(time_with_zone,"%m/%d/%Y %I:%M:%S %p %z").to_time
end
# assuming your database column is called start_time
def js_start_time=(time)
if time.present?
write_attribute :start_time, parse_us_time(time)
else
write_attribute :start_time, time
end
end
# assuming your database column is called start_time
def js_start_time
time = read_attribute :start_time
time_format(time)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment