开发者

Checking a date is between two dates

开发者 https://www.devze.com 2023-04-12 01:32 出处:网络
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.

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(), disco开发者_如何学运维unt.ValidTo()) <= 0
){
   // ALL OK Accept Discount
}
    else 
{
   // Discount is no Longer Valid boo!
}


Try this:

Today = Int(Now());

if ( Today GTE Int(discount.ValidFrom())
 AND Today LTE Int(discount.ValidTo())
   )
{
    // discount is valid
}
else
{
    // no longer valid
}

It works because datetimes are basically just numbers - with the integer/whole part being the days and the decimal/fraction part being the time.

So applying the Int function will convert a datetime to a whole day date, and then you can just do a simple numeric comparison to ensure it is within the ranges.

I find this far more readable and understandable than the DateDiff stuff - there's no confusion over the ordering of things, which I think is the problem with your provided code snippet (you've switched both order and lte/gte; you only wanted to change one or the other).


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消