[英]Rails SQL datetime comparing fails
I am trying to run a comparison on datetime field. 我正在尝试对datetime字段进行比较。 With timezone, the value gets treated as a string.
使用时区,该值将被视为字符串。
DB: MS SQL DB:MS SQL
MyTable.find_by_sql("select * from my_table where my_date > '2012-02-15 16:07:32 UTC'")
ActiveRecord::StatementInvalid: TinyTds::Error: Conversion failed when converting date and/or time from character string.
If I remove the timezone, it returns results. 如果我删除时区,它将返回结果。
MyTable.find_by_sql("select * from my_table where my_date > '2012-02-15 16:07:32'")
How can I do this comparison with '2012-02-15 16:07:32 UTC'
? 如何与
'2012-02-15 16:07:32 UTC'
进行比较? I need to use find_by_sql (fetching data from a different DB. Can't use the rails sql queries). 我需要使用find_by_sql(从其他数据库中获取数据。不能使用rails sql查询)。 Thanks!
谢谢!
You can parse the datetime using: 您可以使用以下方法解析日期时间:
a_datetime = DateTime.strptime('2012-02-15 16:07:32 UTC', '%Y-%m-%d %H:%M:%S %Z')
then format the date using something like: 然后使用以下格式格式化日期:
datetime_str = a_datetime.strftime('%Y-%m-%d %H:%M:%S')
and do your find with: 并通过以下方式进行查找:
MyTable.find_by_sql("select * from my_table where my_date > '#{datetime_str}'")
I haven't tested any of this but should work. 我没有测试过任何一个,但应该可以。
I'm guessing you're calling to_s
on a datetime field resulting in '2012-02-15 16:07:32 UTC'? 我猜您正在在datetime字段上调用
to_s
,从而导致“ 2012-02-15 16:07:32 UTC”?
Try calling to_s(:db)
instead for the database-friendly version. 尝试调用
to_s(:db)
以获得数据库友好版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.