Skip to main content
Known Participant
September 24, 2008
Answered

CFQUERY - comparing same dates?

  • September 24, 2008
  • 3 replies
  • 1092 views
I'm trying to query a range of dates from my database with <cfquery>. I have two variables set to fromDate and toDate which are input values from a FORM (user determines date range).
<cfset start_date = #CREATEODBCDATE(fromDate)#>
<cfset end_date = #CREATEODBCDATE(toDate)#>

My query looks like this:
<cfquery datasource="myds">
SELECT dbID, dbDate
FROM myTable
WHERE dbDate BETWEEN #start_date# AND #end_date#
</cfquery>

This works for every value except when the dbDate is the same as the end_date. There's a problem with TIME. dbDate in my database is of type datetime and holds both a date and time value (ex: 9-24-2008 9:03:58 AM). But the start_date and end_date do not have a time specified from the FORM, so they both display with 12:00:00 AM at the end. So lets say from my FORM, I choose 9-24-2008 for both my start and ending dates. In my query, it looks like...
dbDate BETWEEN 9-24-2008 12:00:00 AM AND 9-24-2008 12:00:00 AM
So if my dbDate's time is anything but 12:00:00 AM, it will not catch it in the comparison. I have to choose 9-25-2008 (9-25-2008 12:00:00 AM) to catch any dates on the 24th (and again, any dates in my database that are 9-25-2008 will now be discluded).

How can write this so the times of the dates are irrelevant? Is there a way to strip the time from dbDate? or to set the time of end_date so it looks like 9-24-2008 11:59:59 PM ? Any help is appreciated.
    This topic has been closed for replies.
    Correct answer Dan_Bracuk
    Change this
    <cfset end_date = #CREATEODBCDATE(toDate)#>
    to this
    <cfset end_date = #CREATEODBCDATE(dateadd("d", 1,toDate))#>

    and this
    WHERE dbDate BETWEEN #start_date# AND #end_date#
    to this
    WHERE dbDate >= #start_date#
    AND dbdate < #end_date#

    That's the logic. To improve it event more, use cfqueryparam.


    3 replies

    Known Participant
    September 24, 2008
    Thanks Dan. That did the trick!
    Dan_BracukCorrect answer
    Inspiring
    September 24, 2008
    Change this
    <cfset end_date = #CREATEODBCDATE(toDate)#>
    to this
    <cfset end_date = #CREATEODBCDATE(dateadd("d", 1,toDate))#>

    and this
    WHERE dbDate BETWEEN #start_date# AND #end_date#
    to this
    WHERE dbDate >= #start_date#
    AND dbdate < #end_date#

    That's the logic. To improve it event more, use cfqueryparam.


    Inspiring
    September 24, 2008
    use your db's date functions to extract just the date part from your
    column and compare that to your form vars. check your db manula for
    which date function to use.

    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com/