The format used when converting and saving a date string to a rails database

My user wants to use the date format% d /% m /% Y (for example: 02/26/2011).

To display dates correctly, I therefore changed to: the default format in environment.rb:

environment.rb :

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
     :default => "%d/%m/%Y"
)

It works fine, but I have one problem when trying to save date strings entered in this format in the database.

It seems that the rails take the lines formed with% m /% d /% Y instead of% d /% m /% Y
04/02/2011 is saved as 2011-04-02 and 26/02/2011 is simply invalid and not saved. ..

I was looking for solutions for this, but the ones I found rely on date changes in my models, such as:

mymodel.rb :   

def datefield_formatted
   datefield.strftime '%m/%d/%Y'
end

def datefield_formatted=(value)
   self.datefield = Time.parse(value)
end


view.html.erb :

<%= form.input :datefield_formatted %>

, ( ).

, Rails "" % d/% m/% Y .

+3
2

, Stackoverlow:

: http://blog.nominet.org.uk/tech/2007/06/14/date-and-time-formating-issues-in-ruby-on-rails/

, : lib/column-patch.rb

class ActiveRecord::ConnectionAdapters::Column

def self.string_to_date(string)
    return string unless string.is_a?(String)

    begin
        return DateTime.strptime(string, ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default])
    rescue
        date_array = ParseDate.parsedate(string)
        # treat 0000-00-00 as nil
        Date.new(date_array[0], date_array[1], date_array[2]) rescue nil
    end
end

def self.string_to_time(string)
    return string unless string.is_a?(String)

    begin
    if dt=Date._strptime(string,ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS[:default])
        return Time.mktime(*dt.values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday))
    else
        raise "Bad format"
    end
    rescue
        time_hash = Date._parse(string)
        time_hash[:sec_fraction] = microseconds(time_hash)
        time_array = time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction)
        # treat 0000-00-00 00:00:00 as nil
        Time.send(ActiveRecord::Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
    end
end

end

config/environment.rb

require 'column-patch'
+1

, sql (.. varchar) % d/% m/% Y. l (date).

date:
  formats:
    default: "%d/%m/%Y"

, l(date)

- activerecord, , :/

+1

Source: https://habr.com/ru/post/1789741/


All Articles