Search code examples
ruby-on-railsrubydatetempus-dominus-datetimepicker

Rails reverses day and month when saving DateTimePicker form field


I am trying to use Tempus Dominus Bootstrap 4 in a form on a Ruby on Rails 5.2 app so the user can select a date. Here is the code:

app/views/events/_form.html.erb

<div class='form-group'>
  <%= f.label :starts_at, 'Start Date and Time', class: 'control-label' %>
  <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
    <%= f.text_field(:starts_at, class: "form-control datetimepicker-input", data: {target:"#datetimepicker1"}) %>
    <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
      <div class="input-group-text"><i class="fas fa-calendar-plus"></i></div>
    </div>
  </div>
</div>

app/assets/javascripts/events.js

$(function () {
  $('#datetimepicker1').datetimepicker();
});

app/controllers/events_controller.rb

  def create
    @event = Event.new(event_params)
    @event.user = current_user
    if @event.save
      redirect_to @event, notice: 'Event was successfully created.' 
    else
      render :new 
    end
  end

I want to submit the format with month first. When I pick a date June 9, 2018 and submit the form, it saves it to the database with the month and day reversed: Sept 6, 2018. When I look at the params after the form is submitted, the format is 06/09/2018 6:00 PM with month first, but Ruby/Rails converts it to a datetime object assuming day first.

How do I tell Ruby that the month is first when converting it to a date object? Can I do something in the controller before saving it?


Solution

  • You can tell Ruby how to read time string:

    DateTime.strptime('06/09/2018', '%m/%d/%Y')
    

    More details you can see in this answer.

    Edited:

    Also, you can set the default date format as there:

    Add this to config/initializers/date_time.rb

    Date::DATE_FORMATS[:default] = "%m/%d/%Y"