简体   繁体   中英

Modifying date to enable search in mysql DateTime format

I have an UI, in which we which we select a date range, and then perform a query to check orders within that range.

So the valid formats accepted are

a) 2013-04-01 17:00:00 - 2013-04-16 18:00:00

b) 2013-04-01 17:00:00 - 2013-04-16

c) 2013-04-01 - 2013-04-16

I split it in ruby to give me start_date and end_date. I don't have to touch the start time, as it ready for the sql query.

But the end_date has to be modified because to perform a ranged query created_at BETWEEN '2013-04-01 17:00:00' AND '2013-04-16' does not give me the results of 16th which should be included in the result set. (As it compares to 2013-04-16 00:00:00)

So this is the working solution, I came up with

end_date = Time.parse(end_date).strftime("%T")=="00:00:00" ? (end_date.to_s) + " 23:59:59" : end_date.to_s

Is there a better way to do this as the above looks quite confusing? (Looking or 1-2 line answers, not more)

You could use the DateTime.parse(str) method:

date_str = "2013-04-16"
date = DateTime.parse(date_str)
#=> Tue, 16 Apr 2013 00:00:00 +0000

date_time_str = "2013-04-16 18:00:00"
date = DateTime.parse(date_time_str)
#=> Tue, 16 Apr 2013 18:00:00 +0000

And then you could test the .hour (or .minute ) and set the end_date to end_of_day if no time was selected:

end_date = (date.hour == 0 && date.minute == 0) ? date.end_of_day : date

Little improvement: You could test if the parsed date is equal to the beginning of this date (no hours/minutes/seconds):

date = DateTime.parse("2013-12-12")
#=> Thu, 12 Dec 2013 00:00:00 +0000
date.beginning_of_day
#=> Thu, 12 Dec 2013 00:00:00 +0000
end_date = (date.beginning_of_day == date) ? date.end_of_day : date
#=> Thu, 12 Dec 2013 23:59:59 +0000

To solve the problem when user enters a DateTime like 2013-04-16 00:00:00 , you can use .include? to check if the string contains the ' 00:00:00 ' part:

date_str = "2013-04-16 00:00:00"
date = DateTime.parse(date_str)

end_date = date if date_str.include?('00:00:00') # means the user explicitly wants the time at 00:00 and 00 second
end_date ||= (date.beginning_of_day == date) ? date.end_of_day : date # set end_date if end_date.nil?

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