1

We have an application where user sets his/her preferred date/time format. User is expected to enter datetime in configured format across the application. Now the problem is for few formats the datetime is parsed wrongly while create/update ActiveRecord.

For example user has set date/time format in hh:mm dd/MM/yyyy. Now if user enters 17:00 04/05/2012 it parses it as 5 PM 5 Apr, 2012 where it should be 5 PM 4 May, 2012

1.8.7 :004 > a = Article.create!(:name => 'a1', :published_at => '17:00 04/05/2012')
 => #<Article id: 2, name: "a1", published_at: "2012-04-05 17:00:00", created_at: "2012-04-16 13:54:36", updated_at: "2012-04-16 13:54:36"> 

I understand that ruby/rails has predefined set of formats against which the date/time string is evaluated and if matches any format in sequence it parses given string with that format.

Another example

1.8.7 :006 > a = Article.create!(:name => 'a1', :published_at => '17:00 15/12/2012')
 => #<Article id: 4, name: "a1", published_at: nil, created_at: "2012-04-16 13:55:43", updated_at: "2012-04-16 13:55:43"> 

Here user entered 15 December, 2012 which was parsed to nil

Someone has already asked similar question here and on ruby-forum but the solution is not applicable in my case as I cannot configure a single datetime format across the application as each user will have his own preferred datetime format.

Now to work with multiple datetime format, I am planning to manipulate it before the params is passed to the ActiveRecord. So the steps would like

  1. Read datetime from params map
  2. Parse it with user's preferred datetime format
  3. Format datetime to the default format used by ActiveRecord
  4. Replace current datetime in params with re-formatted datetime

Here is a snippet of the controller

class ArticlesController < ApplicationController
  before_filter :format_date_time, :only => [:create, :update]
  ...
  ...
  private
    def format_date_time
      datetime = params[:datetime]
      params[:datetime] = DateTime.strptime(datetime, pref_date_time_format).strftime('%c')
    end
end

Would anyone please verify if it is right approach or not? I would be appreciable if someone suggests better ways to accomplish this.

Thanks, Amit Patel

Community
  • 1
  • 1
Amit Patel
  • 15,609
  • 18
  • 68
  • 106
  • [Here](http://stackoverflow.com/a/9725374/517483) is nice explanation how `string` is automatically converted to `date` in `ActiveRecord` – Amit Patel Apr 17 '12 at 11:13
  • Draiken has responded on [ruby-forum](http://www.ruby-forum.com/topic/4085912) to this question – Amit Patel Apr 17 '12 at 14:17

1 Answers1

0

I would go with the approach I mentioned. If anyone has better way please keep sharing.

Thanks, Amit Patel

Amit Patel
  • 15,609
  • 18
  • 68
  • 106