Search code examples
jqueryruby-on-railshtmldatetimehtml-helper

How to save data from html5 input type date/time as Date Time in Rails?


How to handle this two inputs so that both can be sent to the controller and save as Date Time? Or is any helpper/gem looks like date and time picker from html5?

html5 inputs:

%input{:type => "date", :value => "yyyy-mm-dd"}
%input{:type => "time", :value => "07:00"}

standard helper:

= f.datetime_select :time

EDIT: Occurred to me simpler solution I checked and it works with datetime field:

%input{:name => "model[start_at]", :type => "date", :value => "yyyy-mm-dd"}
%input{:name => "model[start_at]", :type => "time", :value => "07:00"}

Solution

  • Assuming that your datetime field is called "started_at", try this:

    1) in your model, define these two methods:

    def started_at_string
      # return started_at datetime converted to a string in a desired format, e.g.:
      self.started_at.strftime(Time::DATE_FORMATS[:default])
    end
    
    started_at_string=(datetime_string)
      self.started_at = Time.zone.parse(datetime_string)
      # also you should process cases when the string is not a datetime
    end
    

    2) in your view:

    f.text_field :started_at_string
    

    3) apply this date picker to the text field: http://jqueryui.com/demos/datepicker/ , and this time picker on top: http://trentrichardson.com/examples/timepicker/ , and you will get a nice datetime picker.

    This method does not work quite nicely for iPhone, though (a screen keyboard and a picker pop up simultaneously and make it difficult to enter a date).