You have two dates/times you want to compare.

You have two dates/times you want to compare.

Use one of ColdFusion's comparison operators in an expression, or use the DateCompare() function.

There are two ways you can compare dates and times in ColdFusion. The first way is to use the tag with a comparison operator such as IS, EQ, NEQ, GT, GTE, LT, LTE, etc:

<cfset date1 = "12/31/1999">
<cfset date2 = "12/31/2002">
<cfif date1 gte date2>
  <cfoutput>#Date1# is greater than or equal to #Date2#</cfoutput>
  <cfoutput>#Date1# is less than #Date2#</cfoutput>

This technique allows you to perform a basic comparison between the two dates/times.

You can perform a more flexible comparison between two dates using the DateCompare() function. This function takes three parameters:

DateCompare(date1, date2, [,datepart])

The function returns -1 if date1 is less than date2, 0 if both date1 and date2 are equal, or 1 if date1 is greater than date2.

What makes this a more flexible method for comparing dates is that the precision of the comparison can be specified using the optional datepart parameter. Valid attributes for datepart are: s (second), n (minute), h (hour), d (day), m (month), and yyyy (year). This means you can compare two dates/times and make the comparison precise to the second, hour, month, year, etc:

<cfset date1 = "12/31/2002 19:00:00">
<cfset date2 = "12/31/2002 21:30:00">
<cfif datecompare(date1, date2, "d") eq 0>
  <cfoutput>#Date1# and #Date2# fall on the same day.</cfoutput>
  <cfoutput>#Date1# and #Date2# don't fall on the same day.</cfoutput>

This example compares two date/time objects, with the precision set to "day". Even though the date/time objects are not exactly equal because of the different time stamps, the example still evaluates True because the comparison's precision is set to "day", making the time stamp insignificant.

This question was written by Rob Brooks-Bilson
It was last updated on January 6, 2006.




comments powered by Disqus