简体   繁体   中英

Rails SQL datetime comparing fails

I am trying to run a comparison on datetime field. With timezone, the value gets treated as a string.

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' ? I need to use find_by_sql (fetching data from a different DB. Can't use the rails sql queries). 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'?

Try calling to_s(:db) instead for the database-friendly version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM