0

I am executing a ruby query:

Timeslot.where("start_date >= ? AND end_date <= ?", Wed, 01 Jul 2015 18:00:00 SGT +08:00, Wed, 01 Jul 2015 21:00:00 SGT +08:00)

I am getting the following error

 SyntaxError: unexpected tCONSTANT, expecting ')'
...AND end_date <= ?", Wed, 01 Jul 2015 18:00:00 SGT +08:00, We...

I suppose it is because I am not escaping the ',' character after Wed. I have two questions:

1) How can I correct this query? 2) I will be replacing Wed, 01 Jul 2015 18:00:00 SGT +08:00 with an actual datetime variable? How can I type this query in the right way if the datetime were variables and not constants?

4
  • start_time= Time.now and end_time = Time.now + 2.hours. Query: Timeslot.where("start_date >= ? AND end_date <= ?", start_time, end_time) Commented Jul 13, 2015 at 10:20
  • 1
    Wed, 01 Jul 2015 18:00:00 SGT +08:00 is neither a valid Ruby date, nor a valid SQL date. Commented Jul 13, 2015 at 10:56
  • @Stefan Yes it is. In the default created_at field of rails models, this is the format you are going to find Commented Jul 13, 2015 at 11:05
  • Exactly, it's a format, i.e. a string representation, not the date itself. Entering Date.today in IRB (or rails console) returns a date that is formatted as Mon, 13 Jul 2015, but entering Mon, 13 Jul 2015 results in a syntax error. Commented Jul 13, 2015 at 11:17

4 Answers 4

1

I would write something like this:

Timeslot.where(
  'start_date >= ? AND end_date <= ?', 
  Date.parse('Wed, 01 Jul 2015 18:00:00 SGT +08:00'),
  Date.parse('Wed, 01 Jul 2015 21:00:00 SGT +08:00')
)
Sign up to request clarification or add additional context in comments.

Comments

0

It seem that you have to convert string date into in the proper date format to perform query operation. Like you have date in UTC time zone, then its better to use Time object and convert into proper date format and use that in your query,

str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10

puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

Comments

0

Did you input parameters Wed, 01 Jul 2015 18:00:00 SGT +08:00 without quotation marks?

I think if you want to use that format. Try this.

"Wed, 01 Jul 2015 18:00:00 SGT +08:00".to_time()
# to_time() method converted to Time Class (timezone is followed by rails setting)

or

"2015-07-01 18:00:00".to_time() # works well.

Comments

0

USE DATETIME ...

start_date=DateTime.parse(Wed, 01 Jul 2015 18:00:00 SGT +08:00)
end_date=DateTime.parse(Wed, 01 Jul 2015 21:00:00 SGT +08:00)
Timeslot.where("start_date >= ? AND end_date <= ?",start_date,end_date)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.