Search code examples
coldfusioncoldfusion-9

Checking a date is between two dates


In ColdFusion I can see the code below, however it does not seem to work. I want to make sure discount is only applied if the valid from and to dates are in range, see below.

if (
  DATEDIFF("d", discount.ValidFrom(), now()) >= 0 
  AND  
  DATEDIFF("d", now(), discount.ValidTo()) <= 0
){
   // ALL OK Accept Discount
}
    else 
{
   // Discount is no Longer Valid boo!
}

Solution

  • Your logic is a bit off. Right now you're returning

    if ({positive_number} and {negative_number})

    which returns false. You should be checking if dateDiff("d", today, discount.to()) is also >= 0.

    <cfscript>
        local = {};
        local.start = createDate( 2011, 10, 01 );
        local.end = createDate( 2011, 10, 30 );
        local.today = now();
        local.valid = false;
    
        if ( (dateDiff("d", local.start, local.today) >= 0) 
                AND (dateDiff("d", local.today, local.end) >= 0) ){
            local.valid = true;
        }
    </cfscript>
    
    <cfoutput>
    x < z: #dateDiff("d", local.start, local.today) GTE 0#
    <hr />
    z < y: #dateDiff("d", local.today, local.end) GTE 0#
    <hr />
    Valid: #local.valid#
    </cfoutput>