SQL Server中的日期时间在Ruby中解析不正确

时间:2013-10-30 17:39:53

标签: ruby sql-server tiny-tds

我正在使用Sinatra编写一个将由Android应用程序使用的Web服务。正在Microsoft SQL Server中使用的数据库。

存储过程调用正在Ruby中进行:

sql = "exec GetTraces '#{id}', '#{start_date}', '#{end_date}'"
result = ConnectionManager.connection.select_all(sql)

GetTraces存储过程返回包含datetime对象的列。当服务器和客户端存在于同一时区时,将返回正确的结果。当服务器和客户端位于不同的时区时,会返回不正确的结果。

例如,如果我使用2013-10-16T06:1500Z作为开始日期而2013-10-16T09:1500Z作为结束日期,那么我应该在该范围内获得日期时间。当客户端和服务器位于不同的时区时,我得到以下内容:

2013-04-09T00:03:11+00:00

我手动测试了存储过程并返回了正确的结果。 Ruby中显示的结果不是从存储过程返回的结果。 Activerecord和/或Tiny tds似乎错误地解析了日期时间。

以下是手动执行存储过程时返回的日期时间示例:

2013-10-16 09:10:51.553

我已使用以下内容覆盖ActiveRecord,以解决以前从SQL Server解析日期时间的问题。我在网上找到了这个解决方案。

module ActiveRecord
  module ConnectionAdapters
    class ColumnWithIdentity
      def cast_to_time(value)
        return value if value.is_a?(Time) or value.is_a?(DateTime)
        time_array = ParseDate.parsedate(value)
        time_array[0] ||= 2000
        time_array[1] ||= 1
        time_array[2] ||= 1
        Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
      end

      def cast_to_datetime(value)
        if value.is_a?(Time) or value.is_a?(DateTime)
          if value.year != 0 and value.month != 0 and value.day != 0
            return value
          else
            return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
          end
        end
        return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
        value
      end
    end
  end
end

对此问题的任何见解表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

我能够通过在Windows而不是Linux上运行脚本来解决此问题。现在返回的日期和时间都是正确的。