Dates before 1970

March 20th, 2006 by papillon

The SQL Server adapter uses the Time class by default to represent datetime columns. This leads to problems when you want to represent dates before the year 1970: You would just get nil values.

I quickly found a similar solution (link lost) (scroll to 11/17/05) on the net and implemented the fix like this in my application_helper.rb file:

# Make the SQL Server Adapter work with dates before 1970
module ActiveRecord
  module ConnectionAdapters
    class ColumnWithIdentity
      def cast_to_time(value)
        return value if value.is_a?(Time)
        time_array = ParseDate.parsedate(value)
        time_array[0] ||= 2000
        time_array[1] ||= 1
        time_array[2] ||= 1
        begin
          Time.send(Base.default_timezone, *time_array)
        rescue
          DateTime.new(time_array[0], time_array[1],
          time_array[2], time_array[3],time_array[4],
          time_array[5]) rescue nil
        end
      end
    end #class ColumnWithIdentity
  end #module ConnectionAdapters
end #module ActiveRecord

This overwrites the standard function of the SQL Server Adapter and returns a DateTime if a normal Time is not enough for the given data.