Fix for ActiveRecord SQL Server adapter dates
A better approach may be to convert this code to use DateTime objects exclusively, but I'm not sure of the speed implications of doing so. The code below first tries to cast the value to a Time object; if that fails, it tries a DateTime object; if that fails, it returns nil.
Stick this in a plugin to use with Rails.
1 2 module ActiveRecord 3 module ConnectionAdapters 4 class ColumnWithIdentity 5 def cast_to_time(value) 6 return value if value.is_a?(Time) or value.is_a?(DateTime) 7 time_array = ParseDate.parsedate(value) 8 time_array[0] ||= 2000 9 time_array[1] ||= 1 10 time_array[2] ||= 1 11 Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil 12 end 13 def cast_to_datetime(value) 14 if value.is_a?(Time) or value.is_a?(DateTime) 15 if value.year != 0 and value.month != 0 and value.day != 0 16 return value 17 else 18 return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil 19 end 20 end 21 return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil 22 value 23 end 24 end 25 end 26 end