Find if DateTime is within period, with optional boundaries?

I made the following code to find if the current date is within a specific period, but with optional boundaries:

func isElligiblePeriod() {
    now = new Date();

    if (!validFrom && !validTo) {
        return true;
    } elseif (now >= validFrom && now <= validTo) {
        return true;
    } elseif (!validTo && now >= validFrom) {
        return true;
    } elseif (!validFrom && now <= validTo) {
        return true;
    }

    return false;
}

Basically, this means that the check will happen if there is a validTo date, a validFrom, both or none. The date is always valid if there are no constraints, can be checked agaisnt each one individually. However, this code is ugly as hell. How can i improve this?

Jon Skeet
people
quotationmark

It looks like you want:

// Check the lower bound, if we have one
if (validFrom && now < validFrom)
{
    return false;
}
// Check the upper bound, if we have one
if (validTo && now > validTo)
{
    return false;
}
return true;

Or as a conditional:

return validFrom && now < validFrom ? false
    : validTo && now > validTo ? false
    : true;

Or as a single condition:

return !(validFrom && now < validFrom)
    && !(validTo && now > validTo);

Or:

return (!validFrom || now >= validFrom)
    && (!validTo || now <= validTo);

Pick whichever approach you find most readable.

Note that it can be really readable if you make sure that validFrom and validTo are always sensible values - with "start of time" and "end of time" values to mean "no from constraint" or "no to constraint". Then you can just have:

return validFrom <= now && now <= validTo;

As an aside, you might want to consider making the upper bound exclusive. That's often (but not always) a good idea - it means that you can have abutting time periods really easily (where the validFrom of one period is the validTo of the previous one).

people

See more on this question at Stackoverflow