Formatting a date string

Hey all,

I have 90 records in database with this kind of format: 2011-05-10
11:23:15

So they are all 2011-05-10 but have different times.

User enters two dates, and just in case the two dates are the same, I
want to ensure I grab all records that span entire day.

So I do this:

unit.reports.reports_for(Date.parse(‘5/10/2011’).beginning_of_day,Date.parse(‘5/10/2011’).end_of_day)

But it returns empty result:

=> []

reports_for scope looks like this:

scope :reports_for, lambda { |start_date, end_date|
where(“time between ? and ?”, start_date, end_date)
}

Problem is the sql looks like this:

SELECT “reports”.* FROM “reports” WHERE (“reports”.unit_id = 1113) AND
(time between ‘2011-10-05 00:00:00.000000’ and ‘2011-10-05
23:59:59.999999’) ORDER BY time desc LIMIT 20 OFFSET 0

Right now the user input looks like this:

unit.reports.reports_for(‘2011/10/05’,‘2011/10/06’)

But I want it to be in this format:

unit.reports.reports_for(‘2011/05/10’,‘2011/06/10’)

thanks for response

This post helped me resolve my issue:

http://www.ruby-forum.com/topic/57923

The key is using the strftime method.

So now I can do this:

units.reports.reports_for(Date.parse(Date.parse(‘5/10/2011’).strftime(‘%Y/
%d/
%m’)).beginning_of_day,Date.parse(Date.parse(‘5/10/2011’).strftime(‘%Y/
%d/%m’)).end_of_day)

On Jan 17, 2012, at 8:26 PM, John M. wrote:

scope :reports_for, lambda { |start_date, end_date|
where(“time between ? and ?”, start_date, end_date)
}

Problem is the sql looks like this:

SELECT “reports”.* FROM “reports” WHERE (“reports”.unit_id = 1113) AND
(time between ‘2011-10-05 00:00:00.000000’ and ‘2011-10-05
23:59:59.999999’) ORDER BY time desc LIMIT 20 OFFSET 0

Have you noticed that these are 2011-10-05 and you said in the first
sentence 2011-05-10.

Depending on which version of Ruby, a/b/YYYY where both a<=12 and b<=12,
sometimes a is the month and sometimes b is the month.

Your first issue is parsing the date format as input from the user.

Take a look at Date#strptime

irb(main):003:0> Date.strptime(‘5/10/2011’, ‘%m/%d/%Y’).to_s
=> “2011-05-10”
irb(main):004:0> Date.strptime(‘5/10/2011’, ‘%d/%m/%Y’).to_s
=> “2011-10-05”