Skip to main content
Inspiring
March 31, 2019
Question

cfif isdefined ... AND ...

  • March 31, 2019
  • 1 reply
  • 2442 views

I have the following cfif statement:

<cfif status.datetime NEQ "" AND dateDiff('d',status.datetime,now()) GT 1 >

It works however in rare occasions status.datetime might not be defined. When I change it to:

<cfif isdefined("status.datetime") AND status.datetime NEQ "" AND dateDiff('d',status.datetime,now()) GT 1 >

it stops working. What am I doing wrong?

Thanks in advance for any help.

Gary

    This topic has been closed for replies.

    1 reply

    James Moberg
    Inspiring
    April 1, 2019

    Add an isDate() or isValid("date") to your statement prior to comparing it to ensure that value is a "date".

    While "" isn't a valid date/time value, the variable could also be NULL if returned from a database query.  (When returned from the database, the value is almost always NULL versus empty/blank.)

    <cfif isdefined("status.datetime") AND isDate(status.datetime) AND dateDiff('d',status.datetime,now()) GT 1>

    ghanna1Author
    Inspiring
    April 1, 2019

    Thanks.  isDate() is a better way to check for the valid date then "". My problem with the isdefined not working is "status" appeared in two different queries.

    WolfShade
    Legend
    April 1, 2019

    For some reason, there has been a long established issue with isDefined() and I would recommend not using it for anything.  Much more precise and less prone to error is StructKeyExists().

    <cfswitch expression="#StructKeyExists(status,'datetime')#">

         <cfcase value="yes">

              <!--- successful code here --->

         </cfcase>

    </cfswitch>

    HTH,

    ^ _ ^