Skip to content

Commit d4d6672

Browse files
committed
Changed cast_to_datetime method to use Time.parse in the
method string_to_time and to return Time objects based on the Base.default_timezone. Time.parse uses the timezone to create the time object while the new_time method discards this timezone info. Also, some code paths were not storing the value as utc even though the Base.default_timezon was utc. TODO: Unsure if the cast_to_time method needs to also use string_to_time
1 parent 90d7844 commit d4d6672

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

lib/active_record/connection_adapters/sqlserver_adapter.rb

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -149,22 +149,9 @@ def type_cast_code(var_name)
149149
class << self
150150
def cast_to_datetime(value)
151151
return value.to_time if value.is_a?(DBI::Timestamp)
152-
153-
if value.is_a?(Time)
154-
if value.year != 0 and value.month != 0 and value.day != 0
155-
return value
156-
else
157-
return new_time(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
158-
end
159-
end
160-
161-
if value.is_a?(DateTime)
162-
return new_time(value.year, value.mon, value.mday, value.hour, value.min, value.sec)
163-
#return DateTime.new(value.year, value.mon, value.day, value.hour, value.min, value.sec)
164-
end
165-
152+
return string_to_time(value) if value.is_a?(Time)
153+
return string_to_time(value) if value.is_a?(DateTime)
166154
return cast_to_time(value) if value.is_a?(String)
167-
168155
value
169156
end
170157

@@ -175,10 +162,14 @@ def cast_to_time(value)
175162
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction)) rescue nil
176163
end
177164

178-
# TODO: Find less hack way to convert DateTime objects into Times
179165
def string_to_time(value)
180-
if value.is_a?(DateTime)
181-
return new_time(value.year, value.mon, value.day, value.hour, value.min, value.sec)
166+
if value.is_a?(DateTime) || value.is_a?(Time)
167+
# The DateTime comes in as '2008-08-08T17:57:28+00:00'
168+
# Original code was taking a UTC DateTime, ignored the time zone by
169+
# creating a localized Time object, ex: 'FRI Aug 08 17:57:28 +04 2008'
170+
# Instead, let Time.parse translate the DateTime string including it's timezone
171+
# If Rails is UTC, call .utc, otherwise return a local time value
172+
return Base.default_timezone == :utc ? Time.parse(value.to_s).utc : Time.parse(value.to_s)
182173
else
183174
super
184175
end

0 commit comments

Comments
 (0)